Skip to content

Instantly share code, notes, and snippets.

@justqyx
Forked from irazasyed/manage-etc-hosts.sh
Last active August 10, 2021 16:50
Show Gist options
  • Save justqyx/38a54135fdcccd11a0e9b75ba7417df8 to your computer and use it in GitHub Desktop.
Save justqyx/38a54135fdcccd11a0e9b75ba7417df8 to your computer and use it in GitHub Desktop.
Bash Script to Manage /etc/hosts file for adding/removing hostnames.
#!/bin/sh
# PATH TO YOUR HOSTS FILE
ETC_HOSTS=/etc/hosts
# DEFAULT IP FOR HOSTNAME
IP="127.0.0.1"
# Hostname to add/remove.
HOSTLINE=$2
echo "+$1+$HOSTLINE+"
removeline() {
if [ -n "$(grep -E "^$HOSTLINE$" $ETC_HOSTS)" ]; then
echo "$HOSTLINE Found in your $ETC_HOSTS, Removing now...";
sudo sed -i '' "/^$HOSTLINE/d" $ETC_HOSTS
else
echo "$HOSTLINE was not found in your $ETC_HOSTS"
fi
}
addline() {
if [ -n "$(grep -E "^$HOSTLINE$" $ETC_HOSTS)" ]; then
echo "$HOSTLINE Found in your $ETC_HOSTS, Removing now...";
else
echo "$HOSTLINE was not found in your $ETC_HOSTS, Adding now...";
sudo -- sh -c -e "echo '$HOSTLINE' >> /etc/hosts";
if [ -n "$(grep -E "^$HOSTLINE$" $ETC_HOSTS)" ]; then
echo "$HOSTLINE was added successfully";
else
echo "Failed to Add $HOSTLINE, Try again!"
fi
fi
}
$1
@justqyx
Copy link
Author

justqyx commented Sep 20, 2016

Usage

./manage-etc-hosts.sh addline "127.0.0.1 test.com"
./manage-etc-hosts.sh removeline "127.0.0.1 test.com"

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