Saturday, October 14, 2023

How To: Change a hostname in *nix

The hostname of most Linux and UNIX systems is a unique identifier set during OS installation. The process of changing this hostname can be accomplished through several methods.

Step 1: Checking the Current Hostname

Before you make any changes, find your current hostname. Use the following command:

hostname
 
Note alternatively you can use 'cat', 'echo', or 'printf' to print hostname too:

echo "$HOSTNAME"
 
printf "%s\n" $HOSTNAME 
cat /etc/hostname

This command will display your current hostname.
 
 
Note there is another command 'hostnamectl' which will print hostname, along with the Chassis, Machine ID, Boot ID, OS (Operating System), Kernel, Architecture, Hardware Vendor & Model:
 
hostnamectl 
 
This command will display additional information your current hostname and the machine.
 
Step 2: Changing the Hostname Temporarily

If you want to change your hostname temporarily (meaning it will revert back to the original after a system reboot), use the following command:

sudo hostname new_hostname

Replace "new_hostname" with your desired hostname.
 
 
Step 3: Changing the Hostname Permanently

To permanently change your hostname, you'll need to edit a specific file (/etc/hostname). To do this, use the nano text editor with the following command:

sudo nano /etc/hostname

hostnamectl


Once inside the file, delete the existing hostname and replace it with your new one. Save and exit by pressing Ctrl+X, then Y, and finally Enter.

Note: In some Linux distributions, you may also need to edit the /etc/hosts file for changes to take effect properly.
 
Step 4: Reboot and Apply Changes

For these changes to take effect we will complete a system reboot, use the following command:

sudo reboot

Now, if you check your hostname again using the "hostname" command, it should display your new hostname.

Please refer to your distribution's documentation for the most accurate instructions. 

To finalize your changes in the entire system, see the next article:

How To: Update your hosts file (it bypasses DNS)