Skip to content

Change hostname

Handle manually

Edit /etc/hostname

sudo vi /etc/hostname

You need to change the lines which point to the old host name in /etc/hosts

sudo vi /etc/hosts

Now, you need to tell the operating system that the host name has changed and the PC has been renamed. You can also reboot.

sudo hostname the-name-you-choose

Script to do this

Note: in some situation this script could have issues.

#!/bin/bash
# Assign existing hostname to $hostn
hostn=$(cat /etc/hostname)

# display existing hostname
echo "Existing hostname is ${hostn}"

# Ask for new hostname $newhost
echo "Enter new hostname: "
read newhost

# Change hostname in /etc/hosts & /etc/hostname
sudo sed -i "s/${hostn}/${newhost}/g" /etc/hosts
sudo sed -i "s/${hostn}/${newhost}/g" /etc/hostname

# Display new hostname
echo "Your new hostname is ${newhost}"

# Press a key to reboot
echo "Press any key to reboot..."
read 1 -p 'Press any key to reboot...';echo
sudo /sbin/reboot