Thursday, July 12, 2012

Change hostname in Ubuntu with POB

Every now and then some services don't work just because Linux has a wrong hostname. A hostname has a short form and a long (FQDN) form. The commands `hostname` and `hostname -f` should not output the same. They correspond to short and long form respectively.

This is a POB recipe to change the host name in Ubuntu (and probably other non Debian systems). I have tested this to remotely change machine names through Remoto-IT.
#!/bin/bash -e
# common/change-hostname.sh

hostname=$1

USAGE="Usage: `basename $0` "

if [ $# -ne "1" ] 
then
 echo $USAGE
 exit 1 
fi

#It is mandatory to provide an FQDN which at the minimum is a subdomain address 
if [[ ! "$hostname" =~ ^.*\..*\..*$ ]]
then
 echo $USAGE
 exit 1
fi

#bash substring removal
short=${hostname%%.*}

sed -i "/$short/d" /etc/hosts
bash -c "echo '127.0.0.1 $hostname $short' >> /etc/hosts"
echo $short > /etc/hostname
hostname -F /etc/hostname
Now you can run it to change your hostname (I use remoto-it to deploy it remotely):
common/change-hostname.sh myhost.sample.com
In your remote host the below commands should correctly output the short name and the FQDN depending on the flags passed:
$ hostname
myhost
$ hostname -f
myhost.sample.com

No comments:

Followers