Change hostname in systemd

After systemd came into the picture of Linux managing the machine and it's services became more easier. Also due to this in every Linux distro it's commands are much similar to manage the machine and it's services. To apply the changes in hostname first need to be super user that is root. As this is a system change so prvilege of super user is require. Below is the command to become root user.

$ su -

Or

$ sudo -i

To change the hostname use the below command of systemd.

# hostnamectl set-hostname [desire hostname]

For example:

# hostnamectl set-hostname linuxmachine

Or you may use sudo tool with above command as shown in below example. Below one line command can also be useful in bash scripting.

$ sudo hostnamectl set-hostname [desire hostname]

For example:

$ sudo hostnamectl set-hostname linuxmachine

Use below command to verify the hostname changed sucessfully in systemd.

$ hostname linuxmachine

There is no require to reboot the machine to apply changes done in hostname. Re-login to see the changes in shell prompt if configured.

After changing the hostname it is always recommended to update hostname in hosts file or if there is no entry for hostname then add hostname beside loopback IP address or else if you want to resolve hostname by any other IP address then add IP address with the new hostname.
Like in below example.

10.0.1.2 linuxmachine

Below is the default hosts file entries are found in CentOS machine which will be without hostname entry but in other OS's like Ubuntu hostname are added in installation in that case when you change the hostname then it is require to update hostname in hosts file to avoid any conflict.

127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 #::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

Hostname entry in hosts file is require when application try to communication with hostname at then machine will try to resolve hostname to IP address from the hosts file.
Edit hosts file with your preferred text editor and change the old hostname with new hostname

# vi /etc/hosts

systemd: /usr/bin/hostnamectl

Design by SanjuD (@ngineerbabu)