Skip to content

Instantly share code, notes, and snippets.

@91xcode
Forked from justqyx/manage-etc-hosts.sh
Created August 10, 2021 16:50
Show Gist options
  • Save 91xcode/1deea1e457676409400e4e2c0ef93309 to your computer and use it in GitHub Desktop.
Save 91xcode/1deea1e457676409400e4e2c0ef93309 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment