How to rename the host name of a Linux computer using a script

linux-penguinThere was a CentOS server where the name needed to be changed. Searches through the Internet revealed a series of commands that would do the trick. This script incorporates these commands into a single utility or bash script.

This may not be all inclusive, but it did work for me on a CentOS 5.8 server. To use this script, simply type ./ [oldhostname] [newhostname]. That is it. The script will do the rest. There is no real error checking in this. If it is used correctly, it will work.


clear				# clear screen
echo -e "\e[3J"		# clear scrollbar

	echo "Usage: $0 [oldhostname] [newhostname]"
	exit 1

# define hosts

# call usage() function if filename not supplied
	[[ $# -le 1 ]] && usage

echo "/proc/sys/kernel/hostname"
echo "----------------------------------------------------------"
echo $newhostname > /proc/sys/kernel/hostname
echo $(cat /proc/sys/kernel/hostname)
echo ""

echo "/etc/hosts"
echo "----------------------------------------------------------"
sed -ie 's/'$oldhostname'/'$newhostname'/g' /etc/hosts
sed 's/'$oldhostname'/'$newhostname'/g' /etc/hosts



In this screenshot, note the usage will appear when a condition is not met to properly use the script. Again, not all conditions have been considered for this quick and dirty script. Also note that the server is named localhost.


Use the script as ./ localhost server01 should rename the server to server01.


A screen will appear with the path and file names of the two files that were modified with their modifications.

Exit out of terminal and login again.


Note that the server has changed to server01.