How to Set or Change Hostname in Linux

The hostname is the name of the machine using which it is identified on a network. It can be anything from a single word string to a complex name. Each hostname has a corresponding numerical address which also identifies the machine on the network.

On the internet, we can consider the main URL of a website as its hostname.

Check Linux Hostname

You can check the current hostname of a Linux machine with the command ‘hostname’.

$ hostname 
Check Hostname of Linux
Check Hostname of Linux

The ‘linuxshelltips‘ is the hostname of my machine and it will be identified in my local network with this name. You can also check the corresponding numerical address with the ‘host‘ command.

$ host linuxshelltips
Check IP Address of Hostname
Check IP Address of Hostname

Set Hostname in Linux

If your machine is not assigned a hostname already, or if you want to change the hostname, here is how you do it.

$ sudo hostname abhispc
Set Hostname
Set Hostname

Open the file ‘/etc/hostname’ in Vim or any editor of your choice.

$ sudo vim /etc/hostname

Replace the existing hostname string with the new hostname and then save and exit the file.

Replace Hostname
Replace Hostname

Finally, open the file ‘/etc/hosts’ and replace the previous hostname with the new hostname.

$ sudo vim /etc/hosts
Replace Hostname to new Hostname
Replace Hostname to new Hostname

Now Save and exit the file.

Now verify with the ‘hostname’ command if it has been changed.

$ hostname
Verify Hostname Changes
Verify Hostname Changes

Set Hostname in Linux Using ‘Hostnamectl’

A hostnamectl is a command-line tool to modify the hostname. Only the newer Linux distributions, Eg. Ubuntu 16.04 and RHEL 7 and onwards, which are based on SystemD, can make use of this tool.

First of all to view details about the host, including hostname, run the following command.

$ hostnamectl
Set Hostname Using Hostnamectl
Set Hostname Using Hostnamectl

Then, to change or set the hostname, run

$ hostnamectl set-hostname abhispc
Change Hostname
Change Hostname
Conclusion

We saw a simple way to modify or set the hostname in Linux. To learn more about the ‘hostname‘ command, make sure you read the man page for the same using command ‘man hostname’.

Thank you for reading and let us know your thoughts and questions in the comments below!

Got something to say? Join the discussion.