Saturday 19 September 2015

Change Hostname in Ubuntu

Manually Edit the hostname

sudo nano /etc/hosts
sudo nano /etc/hostname
sudo reboot

Use sed to change the hostname

sudo sed -i 's/ubuntu/new-hostname/g' /etc/hosts
sudo sed -i 's/ubuntu/new-hostname/g' /etc/hostname
sudo reboot

Write a Bash Script

#!/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/$hostn/$newhost/g" /etc/hostname

#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

Ref:- https://pricklytech.wordpress.com/2013/04/24/ubuntu-change-hostname-permanently-using-the-command-line/

No comments:

Post a Comment