5

In a script I want to be able to write an IP address to somewhere easily, so I thought using dig (or a similar command) with back-ticks.

However the simplest output I've been able to come up to wrt dig parameters is

> dig -t A +noall +answer www.google.com
www.google.com.     300 IN  A   173.194.66.106
www.google.com.     300 IN  A   173.194.66.104

Any way (extra arg, different tool instead of dig?) to get rid of the junk apart from the IP address?? (And please don't tell me to use sed.)

Thanks

knocte
  • 347
  • 1
  • 6
  • 18

3 Answers3

15

On the CentOS box I have to hand

dig +short   www.google.com
74.125.132.147
74.125.132.99
74.125.132.103
74.125.132.104
74.125.132.105
74.125.132.106

If you only want one address then

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

or

dig +short   www.google.com | tail -1
user9517
  • 114,104
  • 20
  • 206
  • 289
  • If the host is CNAME, head -1 will list the CNAME value instead of the IP address. It is also probably best practice to specify the -4 or -6 option explicitly so you get the IP address type you need. – Bill Feb 07 '22 at 16:58
3

sed is a viable option and outright rejecting it is misguided at best.

Anyway, try

dig -t A +noall +answer www.google.com | cut -f 6 | tail -1
Sven
  • 97,248
  • 13
  • 177
  • 225
0

For scripts (particularly if doing reverse-lookup in reports), unless you need to be testing specific DNS functionality, then you would be better to use getent hosts ... That way, if you're running a local DNS caching daemon (eg. nscd or a local caching DNS server such as dnsmasqd) then you get a performance and caching gain, and don't bombard the DNS server with a lot more traffic than necessary.

I've written a description with example in AWK. Hope it helps people avoid some of the pain I'm working with.

Cameron Kerr
  • 3,919
  • 18
  • 24
  • "which getent" being empty leads me to believe it's not POSIX. – user1133275 Jan 11 '18 at 15:17
  • From FreeBSD 11.1 manual page: 'A getent command appeared in NetBSD 3.0, and was imported into FreeBSD 7.0. It was based on the command of the same name in Solaris and Linux.'. That said, 'nslookup', 'host', 'dig' don't appear in standards either (at least the Single UNIX Specification http://pubs.opengroup.org/onlinepubs/9699919799/). The system API will more portable than the utilities in regard to getent(3) and related commands (eg. getaddrbyname(3), getaddrinfo(3). – Cameron Kerr Jan 11 '18 at 21:41