Skip to content

Instantly share code, notes, and snippets.

@ansgar-forestier
Last active April 14, 2023 21:31
Show Gist options
  • Save ansgar-forestier/3436036 to your computer and use it in GitHub Desktop.
Save ansgar-forestier/3436036 to your computer and use it in GitHub Desktop.
Ubuntu change hostname script
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
@AnatolyRugalev
Copy link

This script destroyed my /etc/hosts, so run it carefully. Working solution

@jimbalaya71
Copy link

jimbalaya71 commented Apr 11, 2020

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