How to change the IP address of a Linux computer using a script

linux-penguinThere was a CentOS server where the IP address 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 ./ newip. 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. Basically, the script should find the IP address of eth0 or the primary Ethernet connection. It will then change that value in two files. When complete the network service is restarted. This will kick you out of the system. Log out or close the terminal window. Then log back in using the new IP address. Done.


echo -e "\e[3J"		# Clears scrollbar

	echo "Usage: $0 newip"
	echo "Example: $0"
	exit 1

local_ip_value=$(ifconfig eth0|awk '/inet addr/ {split ($2,A,":"); print A[2]}')

# call usage() function if filename not supplied
	[[ $# -eq 0 ]] && usage

echo "/etc/hosts"
echo "----------------------------------------------------------"
sed -ie 's/'$local_ip_value'/'$new_ip_value'/g' /etc/hosts
sed 's/'$local_ip_value'/'$new_ip_value'/g' /etc/hosts
echo ""
echo "/etc/sysconfig/network-scripts/ifcfg-eth0"
echo "----------------------------------------------------------"
sed -ie 's/'$local_ip_value'/'$new_ip_value'/' /etc/sysconfig/network-scripts/ifcfg-eth0
sed 's/'$local_ip_value'/'$new_ip_value'/' /etc/sysconfig/network-scripts/ifcfg-eth0
echo "The IP of $local_ip_value has successfully been changed to $new_ip_value."
service network restart