Ubuntu – Change Hostname Permanently Using the Command Line


ubuntu-logo

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
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:

sudo sed -i 's/ubuntu/new-hostname/g' /etc/hosts
sudo sed -i 's/ubuntu/new-hostname/g' /etc/hostname

Reboot:

sudo reboot

3. Write a Bash Script

It’s always handy to have a script to do things – so here is a quick bash script that I put together that uses sed to change the hostname and then reboot:

#!/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
read -s -n 1 -p "Press any key to reboot"
sudo reboot

10 thoughts on “Ubuntu – Change Hostname Permanently Using the Command Line

  1. Hello,
    Great script but when i use it, before the ‘Your new hostname is test’ i have a “sudo:unable to resolve test ”
    Thank for help.

    1. Hi Romain – check and make sure that your hostname is the same in /etc/hosts and /etc/hostname. In /etc/hosts the hostname should be after 127.0.0.1 as per the screenshot in my post.

      1. Hi Mike !! Thx for ur answer, i change it but now this “sudo:unable to resolve test ” is after i press a button for reboot.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s