#!/bin/bash # Function to display warnings show_warning() { echo "##############################################" echo "# [WARNING] SYSTEM CONFIGURATION CHANGE #" echo "##############################################" echo "Changing hostname:" echo "$1" echo "--> $2" echo "##############################################" echo } # Initial security check read -p "WARNING: This script will modify system files. Continue? (y/N) " -n 1 -r echo if [[ ! $REPLY =~ ^[Yy]$ ]]; then echo "Installation canceled." exit 1 fi # Get current hostname OLD_HOSTNAME=$(hostname) # Get new hostname (argument or prompt) if [[ -z "$1" ]]; then read -p "Enter new hostname (Use only letters, numbers, and hyphens.): " NEW_HOSTNAME else NEW_HOSTNAME="$1" fi # Validate hostname format if [[ ! "$NEW_HOSTNAME" =~ ^[a-zA-Z0-9-]{1,63}$ ]]; then echo "ERROR: Invalid hostname format. Use only letters, numbers, and hyphens." exit 1 fi # Show change warning show_warning "$OLD_HOSTNAME" "$NEW_HOSTNAME" # Final confirmation read -p "Confirm hostname change? (y/N) " -n 1 -r echo if [[ ! $REPLY =~ ^[Yy]$ ]]; then echo "Installation canceled." exit 1 fi # Backup files BACKUP_TIME=$(date +%Y%m%d-%H%M%S) sudo cp /etc/hostname "/etc/hostname.bak-$BACKUP_TIME" sudo cp /etc/hosts "/etc/hosts.bak-$BACKUP_TIME" # Update system files echo "$NEW_HOSTNAME" | sudo tee /etc/hostname >/dev/null sudo sed -i "s/127\.0\.1\.1.*/127.0.1.1\t$NEW_HOSTNAME/g" /etc/hosts # Apply changes sudo hostnamectl set-hostname "$NEW_HOSTNAME" sudo systemctl restart avahi-daemon 2>/dev/null || true # Completion message echo show_warning "$OLD_HOSTNAME" "$NEW_HOSTNAME" echo "Hostname change complete!" echo "Original files backed up with timestamp: $BACKUP_TIME" echo "A system reboot is recommended for full propagation."