7

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 ?

7

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
  • but how can I put it in a variable – Networker Aug 31 '13 at 1:17
  • @user2683768 - see updates. – slm Aug 31 '13 at 1:19
3

Here you go

dig +short  www.example.com | sed -n '2{p;q}'

-n prevents sed from printing its input by default. 2 causes it to execute p;q on line number 2. p stands for print and q for quit

  • could you explain it to me in short @1_CR – Networker Aug 31 '13 at 1:06
  • This prints the last line, no? echo -e "hi1\nhi2"| sed -n '2{p;q}' gives me hi2. – slm Aug 31 '13 at 1:06
  • @slm thanks for the edit. Explanation added. – iruvar Aug 31 '13 at 1:10
  • I think if you change it from a 2 to a 1 you'll get the first line. – slm Aug 31 '13 at 1:10
  • 1
    Yes, it's scary how much we don't know, isn't it. – slm Aug 31 '13 at 1:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.