Skip to content

Instantly share code, notes, and snippets.

@dknoodle
Created June 5, 2025 14:26
Show Gist options
  • Save dknoodle/c57d6079627c27e992523de08730bc59 to your computer and use it in GitHub Desktop.
Save dknoodle/c57d6079627c27e992523de08730bc59 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Change hostname on Ubuntu/Debian system
# Run with: sudo bash change-hostname.sh new-hostname
set -e
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "Please run with sudo: sudo bash $0 <new-hostname>"
exit 1
fi
# Check if hostname provided
if [ -z "$1" ]; then
echo "Usage: sudo bash $0 <new-hostname>"
echo "Example: sudo bash $0 dk-u-dev-3"
exit 1
fi
NEW_HOSTNAME="$1"
OLD_HOSTNAME=$(hostname)
# Validate hostname
if [[ ! "$NEW_HOSTNAME" =~ ^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$ ]]; then
echo "Error: Invalid hostname. Use only letters, numbers, and hyphens."
echo "Hostname must start with a letter or number."
exit 1
fi
echo "Changing hostname from '$OLD_HOSTNAME' to '$NEW_HOSTNAME'"
# Update hostname file
echo "$NEW_HOSTNAME" > /etc/hostname
# Update hosts file
if grep -q "127.0.1.1" /etc/hosts; then
# Replace existing 127.0.1.1 entry
sed -i "s/127.0.1.1.*/127.0.1.1\t$NEW_HOSTNAME/" /etc/hosts
else
# Add 127.0.1.1 entry if it doesn't exist
echo "127.0.1.1\t$NEW_HOSTNAME" >> /etc/hosts
fi
# Also update any occurrence of old hostname in hosts file
sed -i "s/\b$OLD_HOSTNAME\b/$NEW_HOSTNAME/g" /etc/hosts
# Update current session hostname
hostname "$NEW_HOSTNAME"
# Update systemd if available
if command -v hostnamectl &> /dev/null; then
hostnamectl set-hostname "$NEW_HOSTNAME"
fi
# Update cloud-init if present (for cloud images)
if [ -f /etc/cloud/cloud.cfg ]; then
if grep -q "preserve_hostname: false" /etc/cloud/cloud.cfg; then
sed -i 's/preserve_hostname: false/preserve_hostname: true/' /etc/cloud/cloud.cfg
elif ! grep -q "preserve_hostname:" /etc/cloud/cloud.cfg; then
echo "preserve_hostname: true" >> /etc/cloud/cloud.cfg
fi
fi
echo "✓ Hostname changed successfully!"
echo ""
echo "Changes made:"
echo "- /etc/hostname updated"
echo "- /etc/hosts updated"
echo "- Current session hostname updated"
[ -f /etc/cloud/cloud.cfg ] && echo "- Cloud-init configured to preserve hostname"
echo ""
echo "Please reboot for all changes to take effect: sudo reboot"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment