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 )"

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

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

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
 echo -e "$( hostname -I | awk '{ print $1 }' )\t$NEW_HOSTNAME" >> /etc/hosts

echo "Done."
Scan to Donate Bitcoin
Like this? Donate Bitcoin to at:
Bitcoin 14M4a7UHEX61VoHkyjj4dxbUBNGGz3hmhM
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!

5 thoughts on “A script to update your CentOS Linux server’s hostname

  1. max_militant
    May 12, 2014 at 6:50 am

    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
      May 12, 2014 at 7:03 am

      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.

  2. max_militant
    May 12, 2014 at 8:32 am

    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
      May 14, 2014 at 2:32 am

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

Add Comment Register

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>