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 1HqhvrfNCiZYFWhkfwKUryMCt2fQVmWpjS
Share This Post

About Author: Curtis K

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

  • 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 🙂

  • edlentz

    I tried the script and got “no such file or directory” error. I am trying this on Centos 6.4 Any ideas why? I am really looking for a script to change the hostname to a random name.

  • Thanks for the effort of creating this script and sharing it – worked perfectly for me.

  • Saleem Khan

    Can anyone tell me how to change secondary IP with script?

  • Craig Verburgh


    I changed this a bit to work with Raspberry Pi. All I had to do was:
    1) comment out (or remove) the first sed -i line
    2) make a copy of the if statement (if [ -n “$( grep “$OLD_HOSTNAME” /etc/hosts ) replacing “/etc/hosts” with “/etc/hostname”