Skip to content

hostname Command Cheat Sheet

The hostname command is used to display or set the system's host name. In modern Linux (systemd), hostnamectl is the preferred tool for permanent designation.


Synopsis

hostname [option] [name]
hostnamectl [command]

Viewing Hostname

Simple View

hostname

Network Details

  • Short Name (-s): Strips domain part.
  • FQDN (-f): Fully Qualified Domain Name (requires DNS/hosts setup).
  • IP Address (-i): IP address of the hostname.
hostname -f
# Output: server1.example.com

Changing Hostname (Temporary)

This changes the hostname in the kernel immediately, but it will resolve back to the old one after reboot.

sudo hostname new-server-name

Changing Hostname (Permanent)

Works on Ubuntu, CentOS 7+, Fedora, Debian.

sudo hostnamectl set-hostname new-server-name

2. Manual Method

If hostnamectl is not available:

  1. Edit /etc/hostname:
    echo "new-server-name" | sudo tee /etc/hostname
    
  2. Edit /etc/hosts: You must track the change here too, mapping 127.0.1.1 to the new name.
    127.0.0.1   localhost
    127.0.1.1   new-server-name
    
  3. Reboot or run sudo hostname new-server-name.

hostnamectl Details

hostnamectl tracks three classes of hostnames:

  1. Static: Stored in /etc/hostname (the main one).
  2. Pretty: User-friendly UTF-8 name (e.g., "Bob's Laptop").
  3. Transient: Dynamic name received from DHCP.
hostnamectl status

Set a pretty name:

sudo hostnamectl set-hostname --pretty "Development Server X"


Troubleshooting

"sudo: unable to resolve host"

This error usually happens after changing the hostname but forgetting to update /etc/hosts. Fix: Add the new hostname to the 127.0.0.1 or 127.0.1.1 line in /etc/hosts.


Exit Status

Code Meaning
0 Success
1 Error (Permission denied, invalid name)

Notes

  • Hostnames are conventionally lowercase.
  • Avoid underscores (_) in hostnames as they violate some RFC standards for DNS; use hyphens (-) instead.