Skip to content

Instantly share code, notes, and snippets.

@NotYusta
Last active July 11, 2025 07:29
Show Gist options
  • Save NotYusta/820c96e5220716ef431c3f1942ba700d to your computer and use it in GitHub Desktop.
Save NotYusta/820c96e5220716ef431c3f1942ba700d to your computer and use it in GitHub Desktop.
Set Hostname
#!/bin/bash
# Ensure script is run as root
if [ "$(id -u)" -ne 0 ]; then
echo "❌ Please run this script as root (sudo)."
exit 1
fi
# Check for hostname argument
if [ -z "$1" ]; then
echo "Usage: $0 <new-hostname>"
exit 1
fi
NEW_HOSTNAME="$1"
CURRENT_HOSTNAME=$(hostname)
echo "➡️ Changing hostname from '$CURRENT_HOSTNAME' to '$NEW_HOSTNAME'..."
# Set the hostname
hostnamectl set-hostname "$NEW_HOSTNAME"
echo "$NEW_HOSTNAME" > /etc/hostname
# Update /etc/hosts for 127.0.1.1 (Debian/Ubuntu)
if grep -q "127.0.1.1" /etc/hosts; then
sed -i "s/127.0.1.1[[:space:]]\+$CURRENT_HOSTNAME/127.0.1.1\t$NEW_HOSTNAME/" /etc/hosts
else
echo "127.0.1.1 $NEW_HOSTNAME" >> /etc/hosts
fi
# Optional: update 127.0.0.1 line if hostname appears there
if grep -q "127.0.0.1.*$CURRENT_HOSTNAME" /etc/hosts; then
sed -i "s/\(127.0.0.1.*\)$CURRENT_HOSTNAME/\1$NEW_HOSTNAME/" /etc/hosts
fi
echo "✅ Hostname updated to '$NEW_HOSTNAME'."
reboot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment