How to Use hostname Command in Linux: Syntax and Examples
Use the
hostname command in Linux to display or set the system's hostname. Running hostname alone shows the current hostname, while hostname newname changes it temporarily.Syntax
The basic syntax of the hostname command is:
hostname: Displays the current hostname.hostname [newname]: Sets the hostname temporarily tonewname.hostname -I: Shows the IP addresses assigned to the host.hostname -f: Displays the fully qualified domain name (FQDN).
bash
hostname [options] [new_hostname]
Example
This example shows how to display the current hostname and how to change it temporarily.
bash
hostname
hostname new-hostname
hostnameOutput
my-computer
new-hostname
new-hostname
Common Pitfalls
One common mistake is expecting the hostname change to persist after reboot. The hostname command changes the hostname only temporarily until the system restarts.
To make the change permanent, you must edit system files like /etc/hostname or use system tools like hostnamectl.
bash
hostname permanent-hostname
# This changes hostname only until reboot
# Correct way to set permanent hostname (example for systemd systems):
hostnamectl set-hostname permanent-hostnameQuick Reference
| Option | Description |
|---|---|
| hostname | Show current hostname |
| hostname newname | Set temporary hostname to newname |
| hostname -I | Show all IP addresses |
| hostname -f | Show fully qualified domain name |
| hostnamectl set-hostname name | Set permanent hostname (systemd) |
Key Takeaways
Use
hostname alone to see your current system hostname.Use
hostname newname to change the hostname temporarily until reboot.To make hostname changes permanent, edit system files or use
hostnamectl.Options like
-I and -f help show IP addresses and full domain names.Remember hostname changes via
hostname command do not survive system restarts.