Created
January 5, 2022 15:47
-
-
Save jakoberpf/76b4b820e04b6db101e38e9492f5f35b to your computer and use it in GitHub Desktop.
Add a new host to the /etc/hosts file
This file contains hidden or 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 | |
# insert/update hosts entry | |
ip_address="192.168.x.x" | |
host_name="my.hostname.example.com" | |
# find existing instances in the host file and save the line numbers | |
matches_in_hosts="$(grep -n $host_name /etc/hosts | cut -f1 -d:)" | |
host_entry="${ip_address} ${host_name}" | |
echo "Please enter your password if requested." | |
if [ ! -z "$matches_in_hosts" ] | |
then | |
echo "Updating existing hosts entry." | |
# iterate over the line numbers on which matches were found | |
while read -r line_number; do | |
# replace the text of each line with the desired host entry | |
sudo sed -i '' "${line_number}s/.*/${host_entry} /" /etc/hosts | |
done <<< "$matches_in_hosts" | |
else | |
echo "Adding new hosts entry." | |
echo "$host_entry" | sudo tee -a /etc/hosts > /dev/null | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment