Changing the Hostname in Linux Using hostnamectl
Changing the hostname of a Linux system is a common task for system administrators. The hostname is used to identify the device on a network and is displayed in various places, such as the terminal prompt. While you can change the hostname by editing the /etc/hostname file, using the hostnamectl command offers several advantages. This article will guide you through using hostnamectl to change the hostname and explain why it is preferred over directly editing the /etc/hostname file.Using hostnamectl to Change the Hostname
The hostnamectl command is part of the systemd suite and provides a standardized way to manage hostnames on Linux systems. Here’s how you can use it:- Check the Current Hostname
To view the current hostname, you can use the following command:Code:hostnamectl
- Set a New Hostname
To change the hostname, use the set-hostname option followed by the new hostname. For example, to change the hostname to new-hostname, run:Code:sudo hostnamectl set-hostname new-hostname
- Verify the Change
After setting the new hostname, you can verify the change by running:Code:hostnamectl
- Update the /etc/hosts File
It’s also a good practice to update the /etc/hosts file to reflect the new hostname. Open the file in a text editor:Code:sudo nano /etc/hosts
Code:127.0.1.1 new-hostname
Advantages of Using hostnamectl
Using hostnamectl has several advantages over directly editing the /etc/hostname file:- Atomic Updates
Changes made with hostnamectl are applied instantly across all running system processes, ensuring consistency without requiring a reboot
- Dynamic Hostnames
hostnamectl allows setting transient hostnames that reset on reboot, which is useful for temporary changes
- UTF-8 Support
The command supports UTF-8 characters, allowing for more flexible and descriptive hostnames
- Simplified Management
Using hostnamectl simplifies hostname management by integrating with systemd, ensuring that changes are applied consistently with other system configurations
- No Need to Restart Services
Unlike editing the /etc/hostname file, which may require restarting network services to apply changes, hostnamectl applies changes immediately
You do usually have to log out, and log back in again in order to see the hostname update.