What's the most concise way to resolve a hostname to an IP address in a Bash script? I'm using Arch Linux.
|
With
(Corrected package name according to the comments. As a note other distributions have |
|||||||||||||
|
|
As Heinzi said below, the best way is to use
If +short is unavailable for some reason, any one of the following should work:
If you want to only print one IP, then add the
|
|||||||||||||||
|
|
The following command using
Note:
Note 2: If a hostname has multiple IP addresses (try |
||||
|
|
|
I have a tool on my machine that seems to do the job. The man page shows it seems to come with mysql... Here is how you could use it:
The return value of this tool is different from 0 if the hostname cannot be resolved :
UPDATE On fedora, it comes with mysql-server :
I guess it would create a strange dependency for your script... |
|||||||
|
|
The solutions given so far mostly work in the simpler case: the hostname directly resolves to a single ip address. This might be the only case where you need to resolve hostnames, but if not, bellow is a discussion on some cases that you might need to handle. Chris Down and Heinzi shortly discussed the case where the hostname resovles to more than one ip addresses. In this case (and others bellow), basic scripting under the assumption that a hostname directly resolves to a single ip address may break. Bellow an example with a hostname resolving to more than a single ip address:
But what is
So
But can aliases be chained ? The answer is yes:
I did not find any example where a hostname resolves to an alias that does not resolve to an ip address, but I think the case might occur. More than multiples ip addresses and aliases, is there some other special cases... what about ipv6 ? You could try:
Where the hostname
Again about ipv6, if your host is ipv4 only, you can still resolve ipv6 addresses (tested on a ipv4 only WinXP and with ipv6.google.com, you could try it on Linux). In this case, the resolution succeeds, but a ping fails with an unknown host error message. This might be a case where your scripting fails. I hope those remarks were usefull. |
|||
|
|
To avoid the problem with aliases and always get a single IP address ready for use:
|
|||
|
|
works without dependencies on other systems (and for hosts specified in /etc/hosts) |
||||
|
|
You could use
|
|||||||||||
|