首页 > Sysadmin > 正文

Ways to Check the Hostname on Linux

2026-10-31 Sysadmin

The hostname is a machine identity on the network on Linux. You can usually inspect or temporarily change it with a single command; permanent changes require root privileges.

Kernel view: the hostname command

hostname
hostname -s
hostname -f
hostname -d

Without arguments, hostname prints the kernel-returned hostname, equivalent to reading the result of gethostname(2) [1]. -s is the short name, -f is the FQDN (fully qualified domain name), and -d returns only the DNS domain portion. Verified on WSL: Ubuntu 24.04 returns DESKTOP-COLORFUL for hostname, DESKTOP-COLORFUL.localdomain for hostname -f, and localdomain for hostname -d.

systemd view: hostnamectl

hostnamectl status
hostnamectl --static
hostnamectl --transient

On systemd-based systems, prefer hostnamectl because it separates the three hostname types [2]: --static is the persistent value read from /etc/hostname, and --transient is the runtime fallback from the network layer. Verified on WSL: both hostnamectl --static and --transient return DESKTOP-COLORFUL, indicating no network-layer override.

Where the static name lives

The static hostname is persisted in /etc/hostname, and only root can modify it [3]. Any user can read it directly:

cat /etc/hostname

Verified on WSL: Ubuntu 24.04 defaults to DESKTOP-COLORFUL. Some distributions also write preserve_hostname into /etc/cloud/cloud.cfg (cloud-init) to prevent cloud-init from overwriting your setting.

Temporary vs permanent changes

To change only the current session, run sudo hostname <new>; reboot reverts it [1].

sudo hostnamectl set-hostname prod-web-01

hostnamectl set-hostname updates both the static hostname and /etc/hostname atomically on systemd systems [2]. In this environment, sudo requires an interactive password, so this command has not been executed; confirm rollback steps on a test machine first.

Rollback and troubleshooting

# revert static name to old value
sudo hostnamectl set-hostname old-name
sudo systemctl restart systemd-hostnamed

# confirm all three views agree
hostname
hostnamectl status
cat /etc/hostname

Common gotcha: hostname changes but hostnamectl status still shows the old value — usually because static has not moved, and only the kernel cache changed; restarting or reloading systemd-hostnamed pulls it back to the static value.

Not fully verified: original source linux.zaixianjisuan.com was blocked by Baidu WAF, so this article is based on official manpages and WSL testing only; hostnamectl set-hostname was not actually executed due to sudo password requirements, and is marked as document-checked rather than hands-on verified.


References

Commands tested on WSL Ubuntu 24.04; other items (uninstalled tools/install-time commands) are verified against official documentation only and have not been hands-on executed.