Skip to content

Instantly share code, notes, and snippets.

@zekiahmetbayar
Last active August 2, 2025 18:40
Show Gist options
  • Select an option

  • Save zekiahmetbayar/dc3ccb633710229475bf522c2ea8dc71 to your computer and use it in GitHub Desktop.

Select an option

Save zekiahmetbayar/dc3ccb633710229475bf522c2ea8dc71 to your computer and use it in GitHub Desktop.
Change hostname automatically with bash script
#!/bin/bash
# Usage
## chmod +x hostname_change.sh
## sudo ./hostname_change.sh new_hostname
if [ "$EUID" -ne 0 ]
then echo "Please run as root."
exit
fi
current="$(hostname)"
echo "Current hostname is $current"
ip="$(hostname -I | cut -d" " -f1 | xargs)"
newHostname=$1
echo "New hostname is $newHostname"
echo "Hostname change process has been started..."
echo "Step1 : hostnamectl running..."
hostnamectl set-hostname $newHostname
echo "Step1 successfully finished."
echo "Step2 : Writing new hostname to /etc/hosts"
echo "$ip $newHostname" >> /etc/hosts
echo "Step2 successfully finished."
echo "Hostname successfully changed."
echo "Verifying..."
check=$(hostname)
if [[ "$newHostname" -eq "$check" ]]
then
echo "Hostname successfully changed $current to $check"
echo "Sucessfully verified. Goodbye!"
fi
@c0nsaw
Copy link

c0nsaw commented Nov 8, 2022

sudo ./hostname_change.sh new_ip

should be

sudo ./hostname_change.sh new_hostname

@zekiahmetbayar
Copy link
Author

Hi!,

Thanks for pointing out the error.

I corrected the relevant part 👍 😺

@mahfiaz
Copy link

mahfiaz commented Aug 2, 2025

Simply adding to /etc/hosts is not correct. It leaves the most important line intact:
127.0.1.1 oldhostname

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment