hostname – Display and set the hostname of the system

The hostname command is used to display or set the hostname of the system. The hostname is a label assigned to a device on a network, and it is used to identify the device among other devices on the same network. The hostname is usually a combination of a name and a domain name, separated by a dot.

Overview

To display the current hostname of the system, simply run the hostname command without any arguments:

$ hostname
mycomputer.example.com

To set a new hostname for the system, use the -s option followed by the new hostname:

$ sudo hostname -s newhostname

Note that changing the hostname requires root privileges, so you need to run the command with sudo or as the root user.

If you want to set a fully qualified domain name (FQDN) for the system, use the -F option followed by the FQDN:

$ sudo hostname -F newhostname.example.com

This command will set the hostname to newhostname and the domain name to example.com.

You can also edit the /etc/hostname file directly to change the hostname permanently:

$ sudo nano /etc/hostname

In this file, simply replace the current hostname with the new hostname and save the file.

Options

The following table lists the available options for the hostname command:

Option Description
-s, --short Display or set the short (non-FQDN) hostname
-d, --domain Display the domain name of the system
-f, --fqdn Display the FQDN of the system
-i, --ip-address Display the IP address of the system
-I, --all-ip-addresses Display all IP addresses of the system
-A, --all-fqdns Display all FQDNs of the system
-F, --file Read the new hostname from a file
-h, --help Display help information
-V, --version Display version information

Troubleshooting tips

If you encounter issues when setting the hostname, make sure that the new hostname is a valid hostname according to the rules for hostnames. A valid hostname must be between 1 and 63 characters long and can only contain letters, numbers, and hyphens. It cannot start or end with a hyphen, and it cannot contain consecutive hyphens.

If you set a new hostname using the hostname command, the change will only be temporary and will not persist after a reboot. To make the change permanent, you need to edit the /etc/hostname file as described in the previous section.

Notes

  • The hostname is used by many network services to identify the system, so it is important to set it correctly.
  • The hostname is also used in the command prompt of the shell, so changing the hostname can affect the appearance of the prompt.