• Home
  • Linux Hostname change script

Linux Hostname change script

by:admin April 1, 2025 0 Comments

Linux Hostname change script

Takes the hostname as an argument

Detects the server’s static IP (not 127.0.0.1)

Binds that IP to the new hostname in /etc/hosts

Script: change-hostname.sh

#!/bin/bash

# Check if hostname argument is provided
if [ -z "$1" ]; then
echo "Usage: $0 new-hostname"
exit 1
fi

NEW_HOSTNAME="$1"

# Get the first non-loopback IP address (IPv4)
STATIC_IP=$(hostname -I | awk '{print $1}')

if [ -z "$STATIC_IP" ]; then
echo "❌ Could not detect a static IP address."
exit 2
fi

# Set hostname using hostnamectl
echo "🔧 Setting system hostname to: $NEW_HOSTNAME"
hostnamectl set-hostname "$NEW_HOSTNAME"

# Update /etc/hosts
echo "📝 Updating /etc/hosts"
# Remove existing lines with this IP or hostname
sed -i "/$STATIC_IP/d" /etc/hosts
sed -i "/$NEW_HOSTNAME/d" /etc/hosts

# Add new line with IP and hostname
echo "$STATIC_IP $NEW_HOSTNAME" >> /etc/hosts

# Optional: also keep 127.0.0.1 localhost
if ! grep -q "127.0.0.1" /etc/hosts; then
echo "127.0.0.1 localhost" >> /etc/hosts
fi

# Confirm the change
echo "✅ Hostname updated to: $(hostname)"
echo "📌 Bound to static IP: $STATIC_IP"



🧪 Example usage:

chmod +x change-hostname.sh
sudo ./change-hostname.sh myserver.example.com

Categories:

Leave Comment