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 to Curtis K
Did you like this?
Tip Curtis K with Bitcoin
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!