Shell – How to get the output and test the dig command

shell

when we type " dig +short www.example.com " command
we get something like that:

www.example.com.
192.168.1.1
192.168.1.2
192.168.1.3

I want to get the first address and test it if it is what I want to (192.168.1.1)

How can I get the output of this command, especially the second line by using shell script ?

Best Answer

Something like this will do:

$ dig +short www.google.com | head -1
74.125.225.113

But be careful because most servers that have multiple IP addresses will do some form of round robin at the DNS level so the list is typically rotating every time you run the dig command:

$ dig +short www.google.com
74.125.225.116
74.125.225.112
74.125.225.113
74.125.225.114
74.125.225.115

$ dig +short www.google.com
74.125.225.115
74.125.225.116
74.125.225.112
74.125.225.113
74.125.225.114

$ dig +short www.google.com 
74.125.225.114
74.125.225.115
74.125.225.116
74.125.225.112
74.125.225.113

Notice how the IPs move around from query to query? This is done to balance the load across those servers.

Capturing the IP into a variable

The following command will capture the output of the IP address and put it into a shell variable.

$ IP=$(dig +short www.google.com | head -1)

You can confirm this like so:

$ echo $IP
74.125.225.114