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
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
Display Current Hostname
The most basic use - showing what your system is currently called.
# Display the hostname
hostname
# Alternative methods to check hostname
cat /etc/hostname
hostnamectl status | grep hostname
uname -n
hostnamectl providing the most detailed output on systemd-based systems.
\h to PS1 in their .bashrc: PS1="[\u@\h \W]\$ "
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
# Compare short vs FQDN
echo "Short hostname: $(hostname -s)"
echo "FQDN: $(hostname -f)"
echo "Domain: $(hostname -d)"
hostname -f may fail or return unexpected results.
Display IP Address(es)
Get the IP address(es) associated with your hostname.
# Display primary IP address
hostname -i
# Display ALL IP addresses
hostname -I
-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.
- 192.168.1.100 - Primary network interface (eth0)
- 10.0.0.5 - Secondary interface or VPN
- 172.17.0.1 - Docker bridge network
# 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
Changing Hostname Temporarily
Set a new hostname for the current session (doesn't survive reboot).
# Check current hostname
hostname
# Set new hostname temporarily (requires root)
sudo hostname newserver
# Verify the change
hostname
# After reboot, hostname reverts
# (unless you also update /etc/hostname)
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).
- Testing hostname changes before making them permanent
- Temporary identification during troubleshooting
- Container environments where persistence isn't needed
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."
- Update /etc/hostname file
- Update references in /etc/hosts
- Set hostname for current session
- Optionally restart network services
On systemd-based systems (most modern Linux), hostnamectl set-hostname does all of this automatically and is the recommended method.
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
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
- Multi-server environments
- Centralized logging systems
- Backup and monitoring systems
- Email notifications
- Audit trails
- Log file naming:
$(hostname)_$(date +%Y%m%d).log - Backup file identification
- Report generation with system identification
- Distributed system coordination
- Configuration management
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]\$ "
- 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
\h- Hostname up to first '.'\H- Full hostname (FQDN)\u- Username\W- Current directory basename\w- Full current directory path
Hostname Resolution and /etc/hosts
Understanding and configuring hostname resolution.
# Check current /etc/hosts configuration
cat /etc/hosts
# 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
- 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
# 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
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
- Central monitoring systems
- Automated reporting
- Troubleshooting documentation
- Capacity planning
- Audit compliance
- Run via cron, email report daily
- Called by monitoring system (Nagios, Zabbix)
- Part of incident response documentation
- Automated compliance reporting
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
- 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
- System installation/configuration
- Troubleshooting hostname issues
- Standardizing hostname setup across servers
- Pre-deployment verification
- Training tool for junior administrators
Configuration Files
Contains the system's static hostname (single line, just the hostname):
server01
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
Older systems used this file:
NETWORKING=yes
HOSTNAME=server01.example.com
Additional Information
- 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
- 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
# 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)
- 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
- 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) |