How to get the fully qualified name (FQN) on Unix in a bash script?
Solution 1:
I tried this on CentOS5:
host -TtA $SERVERNAME|grep "has address"|awk '{print $1}'
I have to query my DNS in TCP-Mode. If UDP works in your environment leave away the "T" option.
Note: on an Ubuntu guest (VirtualBox) it won't work:
git@aHostname:~/$ host -TtA $(hostname -s)
Host aHostname not found: 3(NXDOMAIN)
So to cover all the cases:
fqn=$(host -TtA $(hostname -s)|grep "has address"|awk '{print $1}') ; \
if [[ "${fqn}" == "" ]] ; then fqn=$(hostname -s) ; fi ; \
echo "${fqn}"
Solution 2:
Here is one way I found the fqn:
fqn=$(nslookup $(hostname -i)) ; fqn=${fqn##*name = } ; fqn=${fqn%.*} ; echo $fqn
In other words, I had to nslookup
the IP address, which gives me something like:
Server: 128.xxx.yyy.zzz
Address: 128.xxx.yyy.zzz#ww
aa.bb.cc.dd.in-addr.arpa name = myserver.fully.qualified.name.
From there, it was just a question of removing what I didn't want, through bash string manipulations.
Maybe there is a simpler way?
Solution 3:
Your method works only if you have correctly configured your hostname, and have the correct dns settings, etc. If you have all that, then you already know your fqdn.
There is no reliable way to get the fqdn. A single IP address can have several fqdn, and a single fqdn can have several IP addresses... and lots of IP don't have any fqdn at all.
If your machine is directly connected to the internet, just use the IP address and make a reverse DNS request: host 1.2.3.4
But this very often don't give you the desired answer (just try with google for example).
Solution 4:
Doesn't hostname --fqdn
work for you?
Solution 5:
For cross-platform alternative, if you don't mind using python (runs at least on python 2.7 and python 3)
python -c 'import socket; print(socket.getfqdn())'