Star
You must be signed in to star a gist
Bash script to manage /etc/hosts file, adding/removing hostnames.
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
#!/usr/bin/env bash | |
if [ "$1" != "add" ] && [ "$1" != "remove" ] || [ -z "$2" ]; then | |
[ -z "$2" ] && echo "Missing hostname" || echo "Unknown option '$1'" | |
echo "Unknown option '$1'" | |
echo "Usage:" | |
echo " $0 add <hostname>" | |
echo " $0 remove <hostname>" | |
exit 1 | |
fi | |
# Path to your hosts file | |
hostsfile=/etc/hosts | |
# Default IP for hostname | |
ip="127.0.0.1" | |
remove() { | |
hostname=$1 | |
if [ -n "$(grep $hostname $hostsfile)" ]; then | |
echo "$hostname found in your $hostsfile, removing..." | |
sudo sed -i".bak" "/$hostname/d" $hostsfile | |
if [ -n "$(grep -v $hostname $hostsfile)" ]; then | |
echo "$hostname was removed succesfully" | |
else | |
echo "Failed to remove $hostname" | |
fi | |
else | |
echo "$hostname was not found in your $hostsfile" | |
fi | |
} | |
add() { | |
hostname=$1 | |
if [ -n "$(grep $hostname $hostsfile)" ]; then | |
echo "$hostname already exists:" | |
grep $hostname $hostsfile | |
else | |
echo "Adding $hostname to your $hostsfile" | |
sudo -- sh -c -e "echo '$ip $hostname' >> $hostsfile" | |
if [ -n "$(grep $hostname $hostsfile)" ]; then | |
echo "$hostname was added succesfully" | |
grep $hostname $hostsfile | |
else | |
echo "Failed to add $hostname" | |
fi | |
fi | |
} | |
$@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment