🖥️ The hostname Command

Display and Set System Hostname

hostname [OPTION]...
hostname [NEW_HOSTNAME]

Overview

The hostname command displays or sets the system's hostname - the name that identifies your computer on a network. The hostname is fundamental to networking, system identification, and many applications that need to know which system they're running on.

What is a Hostname?

  • A label that identifies a computer on a network
  • Used by DNS, email systems, and many network services
  • Can be a simple name (e.g., "webserver") or fully qualified (e.g., "webserver.example.com")
  • Usually set during system installation but can be changed
  • Stored in /etc/hostname on most Linux systems

Types of Hostnames:

  • Static hostname: Configured in /etc/hostname, persists across reboots
  • Transient hostname: Temporarily set, not persistent
  • Pretty hostname: UTF-8 hostname for presentation (systemd)
  • FQDN (Fully Qualified Domain Name): hostname + domain (e.g., server.example.com)
  • Short hostname: Just the host part without domain (e.g., server)

Common Uses:

  • Display current system hostname
  • Set or change system hostname
  • Get IP addresses associated with hostname
  • Display domain name
  • Show FQDN (fully qualified domain name)
  • Identify systems in scripts and logs
Hostname Resolution:

The hostname is resolved to an IP address through several mechanisms in order: /etc/hosts file, DNS queries, mDNS (Multicast DNS), and other name service switch (NSS) plugins. The order is configured in /etc/nsswitch.conf.

Common Options

Option Description
-s, --short Display short hostname (without domain)
-f, --fqdn, --long Display fully qualified domain name (FQDN)
-d, --domain Display DNS domain name
-i, --ip-address Display IP address(es) of hostname
-I, --all-ip-addresses Display all IP addresses for the host
-A, --all-fqdns Display all FQDNs of the machine
-y, --yp, --nis Display NIS/YP domain name
-b, --boot Set hostname for current boot only (transient)
-F, --file Read hostname from specified file

Detailed Examples

Example 1

Display Current Hostname

The most basic use - showing what your system is currently called.

# Display the hostname hostname
server01
# Alternative methods to check hostname cat /etc/hostname hostnamectl status | grep hostname uname -n
server01 Static hostname: server01.binghamton.edu Icon name: computer-server Operating System: Oracle Linux Server 8.10 Kernel: Linux 5.14.0-362.8.1.el9_3.x86_64 server01
Explanation: The hostname command without options displays the current system hostname. This is the name that identifies your system on the network. The hostname is typically set during installation or by your system administrator. Multiple commands can display this information, with hostnamectl providing the most detailed output on systemd-based systems.
Quick Identification: Many system administrators include the hostname in their shell prompt by adding \h to PS1 in their .bashrc: PS1="[\u@\h \W]\$ "
Example 2

Display FQDN (Fully Qualified Domain Name)

Get the complete hostname including the domain name.

# Display fully qualified domain name hostname -f # Or use --fqdn or --long hostname --fqdn hostname --long
server01.binghamton.edu
Explanation: The FQDN (Fully Qualified Domain Name) includes both the hostname and the domain name. For example, if your hostname is "server01" and your domain is "binghamton.edu", the FQDN is "server01.binghamton.edu". This is important for DNS resolution and email systems.
# Compare short vs FQDN echo "Short hostname: $(hostname -s)" echo "FQDN: $(hostname -f)" echo "Domain: $(hostname -d)"
Short hostname: server01 FQDN: server01.binghamton.edu Domain: binghamton.edu
Note: For the FQDN to work correctly, your hostname must be properly configured in /etc/hosts or resolvable via DNS. If not configured correctly, hostname -f may fail or return unexpected results.
Example 3

Display IP Address(es)

Get the IP address(es) associated with your hostname.

# Display primary IP address hostname -i
192.168.1.100
# Display ALL IP addresses hostname -I
192.168.1.100 10.0.0.5 172.17.0.1
Explanation: The -i option displays the IP address that the hostname resolves to (typically from /etc/hosts or DNS). The -I (capital I) option displays ALL IP addresses assigned to all network interfaces on the system. This is useful for systems with multiple network interfaces or virtual interfaces.
Understanding the Output:
  • 192.168.1.100 - Primary network interface (eth0)
  • 10.0.0.5 - Secondary interface or VPN
  • 172.17.0.1 - Docker bridge network
Alternative Methods:
# Using ip command ip addr show | grep "inet " | awk '{print $2}' # Using hostname with grep hostname -I | tr ' ' '\n' # Get external IP curl -s ifconfig.me
Example 4

Changing Hostname Temporarily

Set a new hostname for the current session (doesn't survive reboot).

# Check current hostname hostname
oldserver
# Set new hostname temporarily (requires root) sudo hostname newserver # Verify the change hostname
newserver
# After reboot, hostname reverts # (unless you also update /etc/hostname)
Explanation: Using hostname newname changes the hostname immediately for the current session. However, this is a transient change - it will be lost when the system reboots. To make a permanent change, you must also update the configuration files (see next example).
Important: Changing the hostname requires root privileges. Some services may need to be restarted to recognize the new hostname. The change is immediate but not persistent across reboots unless you also update /etc/hostname.
When to Use Temporary Changes:
  • Testing hostname changes before making them permanent
  • Temporary identification during troubleshooting
  • Container environments where persistence isn't needed
Example 5

Changing Hostname Permanently

Set a new hostname that persists across reboots.

#!/bin/bash # change-hostname.sh - Safely change hostname permanently OLD_HOSTNAME=$(hostname) NEW_HOSTNAME="webserver01" echo "Current hostname: $OLD_HOSTNAME" echo "New hostname: $NEW_HOSTNAME" echo "" # Method 1: Using hostnamectl (recommended for systemd systems) echo "Setting hostname with hostnamectl..." sudo hostnamectl set-hostname "$NEW_HOSTNAME" # Method 2: Manual method (works on all systems) # Update /etc/hostname echo "$NEW_HOSTNAME" | sudo tee /etc/hostname # Update /etc/hosts sudo sed -i "s/$OLD_HOSTNAME/$NEW_HOSTNAME/g" /etc/hosts # Set for current session sudo hostname "$NEW_HOSTNAME" # Verify changes echo "" echo "Verification:" echo " hostname command: $(hostname)" echo " /etc/hostname: $(cat /etc/hostname)" echo " hostnamectl: $(hostnamectl status | grep 'Static hostname')" echo "" echo "Hostname changed successfully!" echo "Note: Some services may need to be restarted."
Current hostname: oldserver New hostname: webserver01 Setting hostname with hostnamectl... Verification: hostname command: webserver01 /etc/hostname: webserver01 hostnamectl: Static hostname: webserver01 Hostname changed successfully! Note: Some services may need to be restarted.
Explanation: To permanently change the hostname, you need to:
  1. Update /etc/hostname file
  2. Update references in /etc/hosts
  3. Set hostname for current session
  4. Optionally restart network services

On systemd-based systems (most modern Linux), hostnamectl set-hostname does all of this automatically and is the recommended method.

/etc/hosts Configuration:

After changing hostname, update /etc/hosts to include the new name:

127.0.0.1 localhost localhost.localdomain 127.0.1.1 webserver01 webserver01.example.com 192.168.1.100 webserver01.example.com webserver01
Example 6

Using hostname in Scripts

Incorporate hostname information into scripts for system identification and logging.

#!/bin/bash # backup-script.sh - Backup with hostname identification HOSTNAME=$(hostname -s) FQDN=$(hostname -f) IP=$(hostname -i) DATE=$(date +%Y%m%d_%H%M%S) BACKUP_FILE="${HOSTNAME}_backup_${DATE}.tar.gz" LOG_FILE="/var/log/backup.log" # Create backup echo "========================================" | tee -a "$LOG_FILE" echo "Backup Started: $(date)" | tee -a "$LOG_FILE" echo "Host: $FQDN ($IP)" | tee -a "$LOG_FILE" echo "Backup file: $BACKUP_FILE" | tee -a "$LOG_FILE" echo "========================================" | tee -a "$LOG_FILE" tar -czf "/backup/$BACKUP_FILE" /home /etc 2>&1 | tee -a "$LOG_FILE" if [ $? -eq 0 ]; then echo "✓ Backup completed successfully on $HOSTNAME" | tee -a "$LOG_FILE" else echo "✗ Backup failed on $HOSTNAME" | tee -a "$LOG_FILE" exit 1 fi # Send notification email mail -s "Backup completed on $HOSTNAME" admin@example.com <<EOF Backup completed successfully. Host: $FQDN IP: $IP File: $BACKUP_FILE Size: $(du -h /backup/$BACKUP_FILE | cut -f1) Time: $(date) EOF
======================================== Backup Started: Tue Jan 15 14:23:45 EST 2025 Host: server01.binghamton.edu (192.168.1.100) Backup file: server01_backup_20250115_142345.tar.gz ======================================== tar: Removing leading `/' from member names ✓ Backup completed successfully on server01
Explanation: Using hostname in scripts helps identify which system performed an operation, especially important in:
  • Multi-server environments
  • Centralized logging systems
  • Backup and monitoring systems
  • Email notifications
  • Audit trails
Real-World Applications:
  • Log file naming: $(hostname)_$(date +%Y%m%d).log
  • Backup file identification
  • Report generation with system identification
  • Distributed system coordination
  • Configuration management
Example 7

Hostname in Shell Prompt

Display hostname in your bash prompt for constant system awareness.

# Add to ~/.bashrc for permanent change # Simple hostname in prompt export PS1="[\u@\h \W]\$ " # Colored hostname (different colors for prod vs dev) if [[ $(hostname) == *"prod"* ]]; then # Red for production servers - be careful! export PS1="\[\033[01;31m\][\u@\h \W]\$\[\033[00m\] " else # Green for dev/test servers export PS1="\[\033[01;32m\][\u@\h \W]\$\[\033[00m\] " fi # Show full FQDN in prompt export PS1="[\u@$(hostname -f) \W]\$ " # Shortened hostname (first part only) export PS1="[\u@$(hostname -s) \W]\$ "
[craig@server01 ~]$ [craig@server01.binghamton.edu ~]$ [craig@webserver-prod ~]$ (in red for production) [craig@webserver-dev ~]$ (in green for dev)
Explanation: Including the hostname in your shell prompt helps prevent costly mistakes:
  • Always know which server you're working on
  • Prevent running commands on wrong system
  • Color-code production vs development systems
  • Essential when managing multiple SSH sessions
PS1 Variables:
  • \h - Hostname up to first '.'
  • \H - Full hostname (FQDN)
  • \u - Username
  • \W - Current directory basename
  • \w - Full current directory path
Production Safety: Always use different colored prompts for production servers! Many admins use red for production and green/blue for dev/test to provide immediate visual feedback about which environment they're in.
Example 8

Hostname Resolution and /etc/hosts

Understanding and configuring hostname resolution.

# Check current /etc/hosts configuration cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 127.0.1.1 server01 server01.binghamton.edu 192.168.1.100 server01.binghamton.edu server01 192.168.1.101 server02.binghamton.edu server02 192.168.1.102 server03.binghamton.edu server03
# Test hostname resolution getent hosts server01 getent hosts server01.binghamton.edu # Verify FQDN works correctly ping -c 1 $(hostname -f) # Check all names that resolve to this host hostname -A
192.168.1.100 server01.binghamton.edu server01 192.168.1.100 server01.binghamton.edu server01 PING server01.binghamton.edu (192.168.1.100) 56(84) bytes of data. 64 bytes from server01.binghamton.edu (192.168.1.100): icmp_seq=1 ttl=64 time=0.024 ms server01.binghamton.edu server01
Explanation: The /etc/hosts file maps hostnames to IP addresses and is checked before DNS. Proper configuration is crucial:
  • 127.0.0.1: Localhost loopback address
  • 127.0.1.1: Often used for the system hostname
  • Real IP: Should map to FQDN and short hostname
Best Practice /etc/hosts Format:
# Loopback entries 127.0.0.1 localhost ::1 localhost # This server's primary hostname 192.168.1.100 server01.example.com server01 # Other servers (for local resolution) 192.168.1.101 server02.example.com server02 192.168.1.102 db01.example.com db01
Common Mistake: Putting the system's hostname on the 127.0.0.1 line will cause problems with network services. The system hostname should map to its actual network IP address, not localhost!
Example 9

Hostname in Monitoring and Reporting

Using hostname for system monitoring and status reporting.

#!/bin/bash # system-report.sh - Generate system status report HOSTNAME=$(hostname -s) FQDN=$(hostname -f) IP_ADDRESSES=$(hostname -I) DOMAIN=$(hostname -d) # Generate report cat <<EOF ======================================== SYSTEM STATUS REPORT ======================================== Generated: $(date) SYSTEM IDENTIFICATION -------------------- Hostname: $HOSTNAME FQDN: $FQDN Domain: $DOMAIN IP Addresses: $IP_ADDRESSES SYSTEM INFORMATION ------------------ OS: $(cat /etc/os-release | grep PRETTY_NAME | cut -d'"' -f2) Kernel: $(uname -r) Uptime: $(uptime -p) Load Avg: $(uptime | awk -F'load average:' '{print $2}') RESOURCE USAGE -------------- CPU Usage: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)% Memory: $(free -h | awk '/^Mem:/ {print $3 " / " $2}') Disk /: $(df -h / | awk 'NR==2 {print $3 " / " $2 " (" $5 " used)"}') NETWORK STATUS -------------- EOF # Network interfaces ip addr show | awk '/^[0-9]+:/ {print $2}' | while read iface; do iface=${iface%:} ip=$(ip addr show "$iface" | awk '/inet / {print $2}' | cut -d/ -f1) if [ -n "$ip" ]; then echo " $iface: $ip" fi done cat <<EOF ACTIVE SERVICES -------------- $(systemctl list-units --type=service --state=running | grep -E '\.service' | wc -l) services running ======================================== Report for: $FQDN ($HOSTNAME) ======================================== EOF
======================================== SYSTEM STATUS REPORT ======================================== Generated: Tue Jan 15 14:23:45 EST 2025 SYSTEM IDENTIFICATION -------------------- Hostname: server01 FQDN: server01.binghamton.edu Domain: binghamton.edu IP Addresses: 192.168.1.100 10.0.0.5 SYSTEM INFORMATION ------------------ OS: Oracle Linux Server 8.10 Kernel: 5.14.0-362.8.1.el9_3.x86_64 Uptime: up 15 days, 7 hours, 23 minutes Load Avg: 0.15, 0.12, 0.08 RESOURCE USAGE -------------- CPU Usage: 8.5% Memory: 8.2G / 16G Disk /: 85G / 189G (45% used) NETWORK STATUS -------------- eth0: 192.168.1.100 tun0: 10.0.0.5 ACTIVE SERVICES -------------- 87 services running ======================================== Report for: server01.binghamton.edu (server01) ========================================
Explanation: This monitoring script uses hostname extensively to identify the system in reports. This is essential for:
  • Central monitoring systems
  • Automated reporting
  • Troubleshooting documentation
  • Capacity planning
  • Audit compliance
Deployment Scenarios:
  • Run via cron, email report daily
  • Called by monitoring system (Nagios, Zabbix)
  • Part of incident response documentation
  • Automated compliance reporting
Example 10

Complete Hostname Management Script

A comprehensive script for hostname verification, changes, and troubleshooting.

#!/bin/bash # hostname-manager.sh - Complete hostname management utility set -euo pipefail # Colors RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' log_info() { echo -e "${BLUE}[INFO]${NC} $*"; } log_success() { echo -e "${GREEN}[OK]${NC} $*"; } log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; } log_error() { echo -e "${RED}[ERROR]${NC} $*"; } # Check if running as root check_root() { if [ "$EUID" -ne 0 ]; then log_error "This operation requires root privileges" exit 1 fi } # Display current hostname information show_info() { echo "" echo "=========================================" echo "HOSTNAME INFORMATION" echo "=========================================" echo "" log_info "Hostname (short): $(hostname -s)" log_info "Hostname (FQDN): $(hostname -f 2>/dev/null || echo 'Not configured')" log_info "Domain name: $(hostname -d 2>/dev/null || echo 'Not configured')" echo "" log_info "IP Addresses:" hostname -I | tr ' ' '\n' | while read ip; do [ -n "$ip" ] && echo " - $ip" done echo "" log_info "Configuration files:" echo " /etc/hostname: $(cat /etc/hostname 2>/dev/null || echo 'Not found')" echo "" log_info "/etc/hosts entries:" grep -v "^#" /etc/hosts | grep -v "^$" | while read line; do echo " $line" done if command -v hostnamectl &>/dev/null; then echo "" log_info "Systemd hostname status:" hostnamectl status | grep -E "hostname|chassis|Icon name" | sed 's/^/ /' fi } # Verify hostname configuration verify_config() { echo "" echo "=========================================" echo "HOSTNAME VERIFICATION" echo "=========================================" echo "" local errors=0 # Check if /etc/hostname exists if [ ! -f /etc/hostname ]; then log_error "/etc/hostname does not exist" ((errors++)) else log_success "/etc/hostname exists" fi # Check if hostname resolves if hostname -f &>/dev/null; then log_success "FQDN resolves correctly" else log_warn "FQDN resolution failed" ((errors++)) fi # Check if hostname is in /etc/hosts local hn=$(hostname -s) if grep -q "$hn" /etc/hosts; then log_success "Hostname found in /etc/hosts" else log_warn "Hostname not found in /etc/hosts" ((errors++)) fi # Check for localhost on 127.0.0.1 if grep -q "^127.0.0.1.*localhost" /etc/hosts; then log_success "Localhost entry correct" else log_error "Localhost entry missing or incorrect" ((errors++)) fi # Check if hostname on 127.0.0.1 (bad practice) if grep "^127.0.0.1" /etc/hosts | grep -q "$hn"; then log_warn "Hostname should not be on 127.0.0.1 line" log_warn "This can cause network service issues" ((errors++)) fi echo "" if [ $errors -eq 0 ]; then log_success "All checks passed" return 0 else log_warn "Found $errors potential issues" return 1 fi } # Change hostname change_hostname() { local new_hostname="$1" check_root # Validate hostname format if ! echo "$new_hostname" | grep -qE '^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$'; then log_error "Invalid hostname format" log_error "Must be alphanumeric, can contain hyphens, max 63 characters" exit 1 fi local old_hostname=$(hostname -s) echo "" log_info "Changing hostname from '$old_hostname' to '$new_hostname'" echo "" # Backup current configuration cp /etc/hostname /etc/hostname.bak.$(date +%Y%m%d_%H%M%S) cp /etc/hosts /etc/hosts.bak.$(date +%Y%m%d_%H%M%S) log_success "Created configuration backups" # Update /etc/hostname echo "$new_hostname" > /etc/hostname log_success "Updated /etc/hostname" # Update /etc/hosts sed -i "s/\b$old_hostname\b/$new_hostname/g" /etc/hosts log_success "Updated /etc/hosts" # Set for current session hostname "$new_hostname" log_success "Set hostname for current session" # Use hostnamectl if available if command -v hostnamectl &>/dev/null; then hostnamectl set-hostname "$new_hostname" log_success "Updated via hostnamectl" fi echo "" log_success "Hostname changed successfully!" echo "" log_warn "Note: Some services may need to be restarted" log_warn "Consider rebooting to ensure all services recognize the new hostname" } # Main menu show_menu() { echo "" echo "=========================================" echo "HOSTNAME MANAGER" echo "=========================================" echo "" echo "1. Show hostname information" echo "2. Verify hostname configuration" echo "3. Change hostname" echo "4. Exit" echo "" } # Main program if [ $# -eq 0 ]; then while true; do show_menu read -p "Select option [1-4]: " choice case $choice in 1) show_info ;; 2) verify_config ;; 3) read -p "Enter new hostname: " new_name change_hostname "$new_name" ;; 4) log_info "Exiting" exit 0 ;; *) log_error "Invalid option" ;; esac done else # Command-line mode case "$1" in info|show) show_info ;; verify|check) verify_config ;; change|set) if [ $# -lt 2 ]; then log_error "Usage: $0 change <new_hostname>" exit 1 fi change_hostname "$2" ;; *) echo "Usage: $0 {info|verify|change <name>}" exit 1 ;; esac fi
========================================= HOSTNAME MANAGER ========================================= 1. Show hostname information 2. Verify hostname configuration 3. Change hostname 4. Exit Select option [1-4]: 2 ========================================= HOSTNAME VERIFICATION ========================================= [OK] /etc/hostname exists [OK] FQDN resolves correctly [OK] Hostname found in /etc/hosts [OK] Localhost entry correct [OK] All checks passed
Explanation: This comprehensive management script provides:
  • Complete hostname information display
  • Configuration verification with error detection
  • Safe hostname changing with backups
  • Interactive menu or command-line operation
  • Validation of hostname format
  • Integration with systemd (hostnamectl)
  • Helpful warnings and recommendations
Production Use:
  • System installation/configuration
  • Troubleshooting hostname issues
  • Standardizing hostname setup across servers
  • Pre-deployment verification
  • Training tool for junior administrators

Configuration Files

/etc/hostname:

Contains the system's static hostname (single line, just the hostname):

server01
/etc/hosts:

Maps hostnames to IP addresses for local name resolution:

127.0.0.1 localhost localhost.localdomain ::1 localhost localhost.localdomain 192.168.1.100 server01.example.com server01
/etc/sysconfig/network (RHEL/CentOS 6 and earlier):

Older systems used this file:

NETWORKING=yes HOSTNAME=server01.example.com

Additional Information

Hostname Naming Conventions:
  • Use lowercase letters, numbers, and hyphens only
  • Start with a letter, don't end with hyphen
  • Maximum 63 characters per label (part between dots)
  • Total FQDN maximum 253 characters
  • Be descriptive: webserver01, db-primary, etc.
  • Include location/function: nyc-web01, sf-db-master
Common Hostname Problems:
  • Hostname on 127.0.0.1: Causes network service failures
  • Mismatch between files: /etc/hostname vs /etc/hosts
  • No FQDN: Email and SSL certificates may fail
  • DNS vs /etc/hosts: Inconsistent resolution
  • Uppercase letters: Some systems are case-sensitive
Related Commands:
# Display hostname hostname uname -n cat /etc/hostname # Change hostname (systemd) hostnamectl set-hostname newname # Get IP from hostname getent hosts $(hostname) dig $(hostname -f) nslookup $(hostname) # Reverse lookup (IP to hostname) host 192.168.1.100 dig -x 192.168.1.100 # Test hostname resolution ping $(hostname -f)
Services That Depend on Hostname:
  • Email servers: SMTP HELO/EHLO, mail headers
  • SSL/TLS: Certificate subject names
  • Kerberos: Service principals
  • LDAP: Distinguished names
  • Clustering: Node identification
  • Logging: Syslog forwarding, log aggregation
When to Change Hostname:
  • After cloning VMs (avoid duplicate names)
  • System repurposing (webserver → database)
  • Standardizing naming conventions
  • Organizational changes (company rename, rebranding)
  • DNS schema changes

Quick Reference

Task Command
Show hostname hostname
Show short hostname hostname -s
Show FQDN hostname -f
Show domain hostname -d
Show IP address hostname -i
Show all IPs hostname -I
Set hostname (temp) sudo hostname newname
Set hostname (permanent) sudo hostnamectl set-hostname newname
Check config file cat /etc/hostname
Verify resolution getent hosts $(hostname)