The hostname command in Linux: view and change the computer name

On any Linux system, the computer name, also known as hostname, is an identifier that allows distinguishing a machine within a network. Knowing and being able to modify this name is essential for system administrators, developers, and users who work with multi-machine environments.

What is the hostname command?

The hostname command is a tool included in most Linux distributions that allows you to view or set the system’s host name. Although it does not require superuser privileges to read the value, changing it usually requires root permissions.

View the current computer name

To check the current hostname, simply run:

hostname

This will print the name assigned to the kernel at that moment. Another alternative is to read the content of the file /etc/hostname or use the command cat /etc/hostname.

Change the name temporarily

If you want to change the hostname only for the current session (the value will be lost after reboot), you can use:

sudo hostname new-name

After running the command, verify the change with hostname again.

Change the name permanently

To make the change persist after a reboot, you must modify the system’s configuration files. In Debian/Ubuntu-based distributions, the file /etc/hostname contains the static name. Edit it with your favorite editor:

sudo nano /etc/hostname

Replace the existing name with the desired one and save the file. Then, update the file /etc/hosts so that the loopback IP address (127.0.0.1) is associated with the new name:

127.0.0.1   localhost
127.0.0.1   new-name

Finally, restart the hostname service or simply reboot the machine:

sudo systemctl restart systemd-hostnamed

or

sudo reboot

Considerations and best practices

  • Avoid using spaces or special characters in the hostname; use letters, numbers, and hyphens.
  • In cloud or container environments, the hostname may be managed by orchestrators such as Kubernetes or Docker Swarm; in those cases, consult the specific documentation.
  • After changing the hostname, verify that services that depend on the name (e.g., SSH, databases, or internal applications) continue to function correctly.

With these steps, you will be able to view and change your computer's name in Linux safely and effectively, adapting it to the needs of your infrastructure or your daily workflow.

This post is also available in ESPAÑOL.

Leave a Reply

Your email address will not be published. Required fields are marked *

Esta obra está bajo una Licencia Creative Commons Atribución 4.0 Internacional para Francesc Roig francesc@vivaldi.net .