How to Set Up a Hostname via Command Line on Linux

Below are the steps for both temporary and permanent changes, suitable for various Linux distributions.

1. Temporary Hostname Change (Resets on Reboot)

To temporarily change the hostname, use the hostname command. Note that this change will not persist after a reboot.

sudo hostname NEW_HOSTNAME

Replace NEW_HOSTNAME with your desired hostname.

2. Permanent Hostname Change

To make the hostname change persistent across reboots, follow these steps:

a. For Modern Linux Systems Using hostnamectl

Most modern Linux distributions use systemd. Use the following command:

sudo hostnamectl set-hostname NEW_HOSTNAME

This will update the hostname permanently.

b. For Older Linux Systems

  1. Edit the /etc/hostname file:
    sudo nano /etc/hostname

    Replace the existing hostname with NEW_HOSTNAME and save the file.

  2. Update the /etc/hosts file:
    sudo nano /etc/hosts

    Find the line starting with 127.0.0.1 and ensure it maps to the new hostname:

    127.0.0.1   NEW_HOSTNAME
  3. Apply the changes:
    sudo systemctl restart systemd-hostnamed

    Alternatively, reboot your system:

    sudo reboot

3. Verify the Hostname

After making the changes, you can verify the hostname using one of the following commands:

hostname

Or:

hostnamectl

Both commands will display the current hostname.

By following these steps, you can easily set up or change the hostname on your Linux system, whether temporarily or permanently.