How to change system hostname in Linux
Every Linux machine comes with a host name, which is usually configured during system installation. It is stored in /etc/hostname and normally displayed at the terminal as \h in the PS1 environment variable. You can view the current host name of the system via hostname command or by viewing the content of the /etc/hostname file.
The system host name in Linux could be changed via hostname command, but it is not persistent as it will return to the original host name after the system reboots.
user@host:~$ hostname host user@host:~$ sudo hostname newhost user@host:~$ hostname newhost user@host:~$ cat /etc/hostname host
The proper way to change the system host name in Linux and make it persist or permanent is by using hostnamectl tool at the terminal.
Steps to change system hostname in Linux:
-
Launch a terminal application.
-
Check current host name.
user@host:~$ hostname host
-
Change host name with hostnamectl.
user@host:~$ sudo hostnamectl set-hostname newhost
-
Check current hostname again to confirm.
user@host:~$ hostname newhost
-
Check /etc/hostname to ensure change is saved and is persistent.
user@host:~$ cat /etc/hostname newhost
-
Launch new shell to test if change is successful.
user@host:~$ bash user@newhost:~$