Skip to content

Instantly share code, notes, and snippets.

@vmpartner
Last active June 17, 2021 13:24
Show Gist options
  • Save vmpartner/f3b4769b443b0d62c971e83a0f08ad07 to your computer and use it in GitHub Desktop.
Save vmpartner/f3b4769b443b0d62c971e83a0f08ad07 to your computer and use it in GitHub Desktop.
Script for easy change ubuntu hostname
#!/bin/bash
#Assign existing hostname to $hostn
hostn=$(cat /etc/hostname)
#Display existing hostname
echo "Existing hostname is $hostn"
#Ask for new hostname $newhost
echo "Enter new hostname: "
read newhost
#change hostname in /etc/hosts & /etc/hostname
sudo sed -i "s/$hostn/$newhost/g" /etc/hosts
sudo sed -i "s/127.0.0.1 localhost.localdomain localhost/127.0.0.1 localhost.localdomain localhost $newhost/g" /etc/hosts
sudo sed -i "s/$hostn/$newhost/g" /etc/hostname
sudo sed -i "s/preserve_hostname: false/preserve_hostname: true/g" /etc/cloud/cloud.cfg
#display new hostname
echo "Your new hostname is $newhost"
#Press a key to reboot
read -s -n 1 -p "Press any key to reboot"
sudo reboot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment