Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Change hostname of debian based system without a reboot.
# Change the hostname without reboot
# Applies only to debian based OS
# 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
# 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]$ ]]
# 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.
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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.