hostname - Linux


Overview

The hostname command in Linux is used for showing or setting the system’s hostname and domain name. The hostname is the label assigned to the machine on a network, which uniquely identifies it over the network. The command is essential for system administration, network diagnostics, and configuring network settings.

Syntax

The basic syntax of the hostname command is as follows:

hostname [options] [new_name]

If run without options or a new_name, it displays the current system hostname. If new_name is provided, it sets the system’s hostname to new_name, but typically requires superuser privileges.

Options/Flags

  • -a, --alias: Displays the alias name of the host if available.
  • -d, --domain: Shows the DNS domain name of the host.
  • -f, --fqdn, --long: Displays the fully qualified domain name (FQDN).
  • -F, --file: Reads the hostname or NIS domain name from the given file. This option is useful for boot scripts.
  • -i, --ip-address: Displays the IP addresses associated with the hostname.
  • -I, --all-ip-addresses: Outputs all network addresses of the host.
  • -s, --short: Displays the short host name. This is the hostname up to the first ..
  • -y, --yp, --nis: Shows the NIS/YP domain name of the host.

Examples

1. Display the current hostname:

hostname

2. Set a new hostname (as superuser):

sudo hostname new-hostname

3. Display the fully qualified domain name:

hostname -f

4. Read and set hostname from a file:

sudo hostname -F /etc/hostname

5. Display all network addresses of the host:

hostname -I

Common Issues

  • Permission Denied: Trying to set the hostname without sufficient privileges will result in a “Permission denied” error. Use sudo to run the command.
  • Non-Persistent Changes: On most systems, changes made using hostname are not persistent through reboots. To make changes permanent, you may need to edit /etc/hostname or a similar configuration file depending on the distribution.
  • Network Issues: Misconfiguration or DNS issues might prevent the hostname from resolving correctly. Always ensure DNS settings are correct.

Integration

The hostname command can be used in conjunction with other commands for advanced system management and network diagnostic tasks. Example in a script:

#!/bin/bash
echo "Current Hostname:"
hostname
echo "Changing Hostname..."
sudo hostname new-hostname
echo "Hostname after change:"
hostname

Combine with grep or other commands to filter specific information:

hostname -I | grep -v "127.0.0.1"
  • hosts: Tool for maintaining the /etc/hosts file.
  • dnsdomainname: Displays the system’s DNS domain name.
  • nmap: Network exploration tool and security / port scanner, useful to check open ports on the host based on IP addresses shown by hostname.

Further reading and more detailed information can be found in the man pages (man hostname) or online resources such as Linux manual pages.