Created
September 24, 2015 02:30
-
-
Save ralavay/aa57e4bf0b1b9fd2dea0 to your computer and use it in GitHub Desktop.
Change Ubuntu hostname
This file contains hidden or 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
#!/bin/bash | |
# | |
# Change hostname for Ubuntu host | |
OLD_NAME=$(hostname) | |
echo "- Current hostname is: $OLD_NAME" | |
read -p "- Please input new hostname: " NEW_NAME | |
update_ect_hostname() { | |
sudo hostname $NEW_NAME | |
sudo bash -c "echo $NEW_NAME > /etc/hostname" | |
} | |
update_etc_hosts() { | |
# Insert the line "127.0.1.1 <host_name>"" into /etc/hosts | |
is_configured=$(grep -E "127.0.1.1.*$NEW_NAME" /etc/hosts) | |
if [ "$is_configured" = "" ]; then | |
is_set_with_other_name=$(grep -E "127.0.1.1" /etc/hosts) | |
if [ "$is_set_with_other_name" = "" ]; then | |
sudo sed -i "2i127.0.1.1 $NEW_NAME" /etc/hosts | |
else | |
sudo sed -i "s/^127.0.1.1.*$/127.0.1.1 $NEW_NAME/g" /etc/hosts | |
fi | |
fi | |
} | |
if [ $NEW_NAME = "" ]; then | |
echo "- Please enter the new hostname!!" | |
exit 1 | |
fi | |
echo "- Updating with new hostname: $NEW_NAME" | |
update_etc_hosts | |
update_ect_hostname | |
echo "- Current hostname is: $(hostname)" | |
echo "--- DONE ---" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment