Skip to content

Instantly share code, notes, and snippets.

@richarddewit
Forked from irazasyed/manage-etc-hosts.sh
Last active March 8, 2019 00:24
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save richarddewit/b6f92057e8fe039bc9b28dd3544c824a to your computer and use it in GitHub Desktop.
Bash script to manage /etc/hosts file, adding/removing hostnames.
#!/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