Last active
January 24, 2024 07:06
-
-
Save zekiahmetbayar/dc3ccb633710229475bf522c2ea8dc71 to your computer and use it in GitHub Desktop.
Change hostname automatically with bash script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
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
sudo ./hostname_change.sh new_ip
should be
sudo ./hostname_change.sh new_hostname