20

On Alpine Linux, I'd like to know how to extract just the IP address from a DNS / dig query. The query I'm running looks like this:

lab-1:/var/# dig +answer smtp.mydomain.net +short   
smtp.ggs.mydomain.net
10.11.11.11

I'd like to be able to get just the IP address returned. I'm currently playing around with the bash pipe and the awk command. But so far, nothing I've tried is working.

Thanks.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
dot
  • 685
  • 5
  • 11
  • 22

2 Answers2

29

I believe dig +short outputs two lines for you because the domain you query, smtp.mydomain.net is a CNAME for smtp.ggs.mydomain.net, and dig prints the intermediate resolution step.

You can probably rely on the last line from dig's output being the IP you want, though, and therefore the following should do:

dig +short smtp.mydomain.net | tail -n1
dhag
  • 15,440
  • 4
  • 54
  • 65
8

@dhag's answer sounds good; if you do not want to “rely on the last line from dig's output being the IP” you can use grep to extract just the numerical IP address:

dig +short smtp.mydomain.net | grep '^[.0-9]*$'
Renardo
  • 294
  • 1
  • 2