A script to update your CentOS Linux server’s hostname

Want to quickly change the hostname of your server? Use this simple script:

#!/usr/bin/env bash

OLD_HOSTNAME="$( hostname )"
NEW_HOSTNAME="$1"

if [ -z "$NEW_HOSTNAME" ]; then
 echo -n "Please enter new hostname: "
 read NEW_HOSTNAME < /dev/tty
fi

if [ -z "$NEW_HOSTNAME" ]; then
 echo "Error: no hostname entered. Exiting."
 exit 1
fi

echo "Changing hostname from $OLD_HOSTNAME to $NEW_HOSTNAME..."

hostname "$NEW_HOSTNAME"

sed -i "s/HOSTNAME=.*/HOSTNAME=$NEW_HOSTNAME/g" /etc/sysconfig/network

if [ -n "$( grep "$OLD_HOSTNAME" /etc/hosts )" ]; then
 sed -i "s/$OLD_HOSTNAME/$NEW_HOSTNAME/g" /etc/hosts
else
 echo -e "$( hostname -I | awk '{ print $1 }' )\t$NEW_HOSTNAME" >> /etc/hosts
fi

echo "Done."
Scan to Donate Bitcoin
Like this? Donate Bitcoin to at:
Bitcoin 14M4a7UHEX61VoHkyjj4dxbUBNGGz3hmhM
Donate
Share This Post

About Author: Curtis K

Hi! My name is Curtis, and I am the creator of CentOS Blog. Please feel free to comment any suggestions, feedback or questions on my posts!

  • Pingback: How to change hostname on CentOS Linux - CentOS Blog

  • max_militant

    Line 16 has uneaven number of “, and since there might already be a hostname entry in the hosts file, sed might be a good way to go there also. But a supernice inspiration.

    • centosblog

      Thanks for letting me know, max! I’ve updated the code. Agreed – I should also add sed to remove any reference to the old hostname in /etc/hosts.

  • max_militant

    sed -i “s/$HOSTNAME/$NEW_HOSTNAME/g” /etc/hosts ?

    (I haven’t checked it, since I’m in a meeting right now, but that might do the job, if we are sure that the name only is repesented once. Otherwise a check for the inet address might be required).

    • centosblog

      Thanks Max, I’ve updated the script now :)