Script Shell Extracting hostname

Hi all,
Please i have to get hostname of an ip address (172.16.68.4). so i have used the command 'host'

host $ipaddr  >> iptohostname.txt

Here is my file: iptohostname.txt

4.68.16.172.in-addr.arpa domain name pointer g-4.xxx.yyyy.zz.
3.68.16.172.in-addr.arpa domain name pointer g-3.xxx.yyyy.zz.

Please, how can i extract the hostname ?
i try with this script

    hostname=$(grep -e $ipaddr "iptohostname.txt" | awk '{ print $1; }')
    echo "here"
    echo $hostname

but, it display nothing.

Thanks a lot for help.
Best Regards.

If you have ipaddr as 4.68.16.172 and trying to fetch as below:-

4.68.16.172.in-addr.arpa

Then use:-

cat iptohostname.txt | grep "$ipaddr" | awk '{ print $1}'

Thanks

The IP address is reversed in the file !
i try to fetch "172.16.68.4"

How about

host 72.21.206.6 | awk '{print $NF}'
1 Like

Thank you so much for help.

host 72.21.206.6 | awk '{print $NF}'
206-6.amazon.com.

Please, how can i delete the last point ? i'd like only the hostname.

Thank you so much for help.
Kind regards.

host 72.21.206.6 | awk '{print substr($NF,1,length($NF)-1)}'
1 Like

Thank you so much for help.
Kind Regards.

---------- Post updated at 05:55 AM ---------- Previous update was at 04:50 AM ----------

Hi,

Please, i have another question in the same context: how can i get the hostname of the machine i work on ?

Here is my script that i try to complete:

    hostname=$(host $ipaddr | awk '{print substr($NF,1,length($NF)-1)}')
    echo $hostname
    $h= get the current hostname
    if [ $hostname -ne $h ]
    then
    //instructions
    fi

Thank you so much.
Best regards.

host localhost

Did you consider the hostname command?

Hello All,

We should be little careful with command hostname as if by mistakenly(eg-> hostname NEW_NAME) we have given something like typo etc with it then it will set the hostname of the system to NEW_NAME(Which we had given as typo/unintentionally). This is active right away and will remain like that until the system will be rebooted (because at system boot it will set this from some particular file configurations). Debian based systems use the file /etc/hostname to read the hostname of the system at boot time and set it up using the init script /etc/init.d/hostname.sh . But off course we should be root for same.

Thanks,
R. Singh

1 Like

Resolved with :

 hostname -f

On some Unix OS the
Linux command hostname -f sets the hostname to -f !
I usually prefer host `uname -n` plus the just discussed filtering.