Skip to content

Instantly share code, notes, and snippets.

@ralavay
Created September 24, 2015 02:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralavay/aa57e4bf0b1b9fd2dea0 to your computer and use it in GitHub Desktop.
Save ralavay/aa57e4bf0b1b9fd2dea0 to your computer and use it in GitHub Desktop.
Change Ubuntu hostname
#!/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