Skip to content

Instantly share code, notes, and snippets.

@skamithi
Last active January 4, 2016 03:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save skamithi/8561502 to your computer and use it in GitHub Desktop.
Save skamithi/8561502 to your computer and use it in GitHub Desktop.
Change hostname of debian based system without a reboot.
#!/bin/bash
# Change the hostname without reboot
# Applies only to debian based OS
# TODO
# Understand common practises in setting hostnames in /etc/hosts
# in a typical production setting.
die () {
echo >&2 "$@"
exit 1
}
[ "$#" -eq 1 ] || die "new hostname is required"
# Help text
if [ "$1" == '-h' ]; then
echo "Usage: `basename $0` [newhostname]
Change hostname without a reboot"
exit 0
fi
OLD_HOSTNAME=`/bin/hostname`
NEW_HOSTNAME=$1
# Yes/no, yes/no, yes/no.. :)
read -p "Change Hostname from '${OLD_HOSTNAME}' to '${NEW_HOSTNAME}'
ARE YOU SURE? [y/N] " -n 2 -r
if [[ $REPLY =~ ^[yY]$ ]]
then
# change runtime hostname
hostname $1
cp /etc/hostname /etc/hostname.bak
echo $NEW_HOSTNAME > /etc/hostname
# change hostname in host table. Looks like a Debian thing.
# http://www.debian.org/doc/manuals/debian-reference/ch05.en.html#_the_hostname_resolution
cp /etc/hosts /etc/hosts.bak
sed -i "/127\.0\.1\.1/ s/${OLD_HOSTNAME}/${NEW_HOSTNAME}/" /etc/hosts
echo \
"Hostname changed to '${NEW_HOSTNAME}'
If the hostname is present in the bash prompt.
Log out and log back in"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment