script / command to get IPs from list of hostnames and combine into a single file

dig has a +short option that makes it produce only the resulting IP addresses and nothing else.


This code:

for h in google.com yahoo.com notfound.nosuch; do
  printf '%s = ' "$h"
  printf '%s' "$(dig +short "$h")" | tr '\n' ,
  echo
done

Produces the output:

google.com = 108.177.112.102,108.177.112.139,108.177.112.101,108.177.112.138,108.177.112.100,108.177.112.113
yahoo.com = 98.138.252.38,98.139.180.180,206.190.39.42
notfound.nosuch = 

By contrast, this code:

for h in google.com yahoo.com notfound.nosuch; do
  printf "$h = %s\\n" $(dig +short "$h")
done

Produces the output:

google.com = 108.177.112.138
google.com = 108.177.112.100
google.com = 108.177.112.101
google.com = 108.177.112.113
google.com = 108.177.112.139
google.com = 108.177.112.102
yahoo.com = 98.139.180.180
yahoo.com = 206.190.39.42
yahoo.com = 98.138.252.38
notfound.nosuch = 

To read the hostnames from a file, replace the for lines in either of the above code snippets with for h in $(cat hostlist.txt); do — although you may want to add some input validation. Up to you.


Take your pick. If you want another format, please comment.


Note: if all you want is the IP addresses and you don't care about having the hostnames included in the output, then all you need is:

dig +short $(cat hostlist.txt)

Bear in mind, though, that any hostnames that don't appear in DNS will be silently ignored with this command.


I'm not sure of the implications of using nslookup over dig, but I think this might work:

for i in `cat linux.hosts`; do nslookup $i | grep ^Name -A1| awk '{print $2}';echo;done > outputfile