0

I'm trying to store ip addresses given by host, but host actually gives a string saying host-name has address ip-address as many times as many addresses it finds. So my question is can I somehow access the addresses only, without splitting strings and looking for ip addresses? What I've tried so far looks like this

ip=$(host "$candidate")

IFS="s " read -ra ADDR <<< "$ip"
for i in "${ADDR[@]}"; do
    echo "$i"
done

where $candidate holds the host name, but I couldn't really put it to work. Any ideas?

1
  • if you have ssh access keys set from source/target candidate server for password less access, you can do: ip=$(ssh user@$candidate "hostname -i") Commented Sep 16, 2014 at 22:18

2 Answers 2

2

You can use a different DNS lookup tool, such as dig:

$ foo=($(dig google.com +short))
$ printf '%s\n' "${foo[@]}"
74.125.228.196
74.125.228.206
74.125.228.200
74.125.228.198
74.125.228.193
74.125.228.192
74.125.228.199
74.125.228.197
74.125.228.201
74.125.228.195
74.125.228.194

If you must use host, then you will have to do string splitting:

foo=()
while read -r _ _ _ addr; do
    foo+=("$addr")
done < <(host -t A google.com)
printf '%s\n' "${foo[@]}"
Sign up to request clarification or add additional context in comments.

1 Comment

With bash 4 or newer, readarray is available: readarray -t foo < <(dig google.com +short); this skips some bugs your first answer has around glob expansion and odd IFS values. That said, +1 for suggesting dig +short.
1

You can isolate the IP address using parameter expansion/substring extraction as follows:

#!/bin/bash

while read -r line; do 
    array+=( ${line##* } )      # substring extraction for IP only
done < <(host -t A google.com)

for i in ${array[@]}; do
    echo "$i"
done

Output:

$ bash getip.sh
173.194.115.36
173.194.115.35
173.194.115.40
173.194.115.37
173.194.115.34
173.194.115.39
173.194.115.41
173.194.115.46
173.194.115.33
173.194.115.38
173.194.115.32

You can accomplish the same thing with string substitution:

    array+=( ${line//*\ /} )      # string substitution for IP only

4 Comments

Quote your expansions -- for i in "${array[@]}", or else you've written an equivalent to for i in ${array[*]}.
similarly: array+=( "${line##* }" ), if you want one array entry per line.
Alternately: while IFS=' ' read -r ip _; do array+=( "$ip" ); done strips off everything after the first ` ` implicitly, without the PE needed, by putting that content into _.
Yes, agree, but the output from hosts is of the form google.com has address 173.194.115.41 which would lead to a read -r _ _ _ IP as indicated in the other answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.