Last active
April 14, 2023 21:31
-
-
Save ansgar-forestier/3436036 to your computer and use it in GitHub Desktop.
Ubuntu change hostname script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if [ ! -n "$1" ] | |
then | |
echo 'Missed argument : hostname' | |
exit 1 | |
fi | |
if [ "$(id -u)" != "0" ]; then | |
echo "Sorry, you are not root." | |
exit 1 | |
fi | |
hostname $1 | |
chmod 777 /etc/hostname /etc/hosts | |
sed "s/template/$1/g" /etc/hosts > /home/user/hosts.out | |
rm /etc/hosts | |
mv /home/user/hosts.out /etc/hosts | |
echo "$1" > /etc/hostname | |
chmod 644 /etc/hostname /etc/hosts | |
service hostname down | |
service hostname start | |
dhclient |
DO NOT RUN THE ABOVE SCRIPT!!! The below script was tested on Ubuntu 16.04 several times with no issues.
#!/bin/bash
if [ ! -n "$1" ] ; then
echo 'Missing argument: new_hostname'
exit 1
fi
if [ "$(id -u)" != "0" ] ; then
echo "Sorry, you are not root."
exit 2
fi
CUR_HOSTNAME=$(cat /etc/hostname)
NEW_HOSTNAME=$1
# Display the current hostname
echo "The current hostname is $CUR_HOSTNAME"
# Change the hostname
hostnamectl set-hostname $NEW_HOSTNAME
hostname $NEW_HOSTNAME
# Change hostname in /etc/hosts & /etc/hostname
sudo sed -i "s/$CUR_HOSTNAME/$NEW_HOSTNAME/g" /etc/hosts
sudo sed -i "s/$CUR_HOSTNAME/$NEW_HOSTNAME/g" /etc/hostname
# Display new hostname
echo "The new hostname is $NEW_HOSTNAME"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script destroyed my
/etc/hosts
, so run it carefully. Working solution