Ubuntu – Change Hostname Permanently Using the Command Line

On Ubuntu the hostname is stored in both the /etc/hosts and /etc/hostname files. There are several ways that we can change the hostname in these files.

1. Manually Edit the hostname

We can manually edit these files using a basic text editor like nano:

sudo nano /etc/hosts
sudo nano /etc/hostname

In /etc/hostname simply overwrite the existing hostname with a new one. In /etc/hosts you will find the hostname on the line beginning 127.0.0.1 – overwrite only the hostname with the new one, and then reboot.

Editing /etc/hosts using nano

sudo reboot

2. Use sed to change the hostname

Another way to achieve the same goal is to use the sed command to replace the existing hostname with a new one.

For example, my Ubuntu Server has the default hostname of ‘ubuntu’.

Use the hostname command to check what your hostname is.

With sed we can look for our hostname (in /etc/hosts and /etc/hostname) and then replace it with the desired new-hostname: