Skip to content

Instantly share code, notes, and snippets.

@zekiahmetbayar
Last active January 24, 2024 07:06
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zekiahmetbayar/dc3ccb633710229475bf522c2ea8dc71 to your computer and use it in GitHub Desktop.
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 👍 😺

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