Skip to content

Instantly share code, notes, and snippets.

@irazasyed
Created March 7, 2015 09:16
Show Gist options
  • Save irazasyed/a7b0a079e7727a4315b9 to your computer and use it in GitHub Desktop.
Save irazasyed/a7b0a079e7727a4315b9 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.
HOSTNAME=$1
function removehost() {
if [ -n "$(grep $HOSTNAME /etc/hosts)" ]
then
echo "$HOSTNAME Found in your $ETC_HOSTS, Removing now...";
sudo sed -i".bak" "/$HOSTNAME/d" $ETC_HOSTS
else
echo "$HOSTNAME was not found in your $ETC_HOSTS";
fi
}
function addhost() {
HOSTNAME=$1
HOSTS_LINE="$IP\t$HOSTNAME"
if [ -n "$(grep $HOSTNAME /etc/hosts)" ]
then
echo "$HOSTNAME already exists : $(grep $HOSTNAME $ETC_HOSTS)"
else
echo "Adding $HOSTNAME to your $ETC_HOSTS";
sudo -- sh -c -e "echo '$HOSTS_LINE' >> /etc/hosts";
if [ -n "$(grep $HOSTNAME /etc/hosts)" ]
then
echo "$HOSTNAME was added succesfully \n $(grep $HOSTNAME /etc/hosts)";
else
echo "Failed to Add $HOSTNAME, Try again!";
fi
fi
}
@cjgordon
Copy link

cjgordon commented Jul 28, 2024

@kucerarichard in your script I needed to change the msg function from 'exit 0' to 'return' so that it wouldn't exit unless run with verbose flag.

function msg() {
MESSAGE=$1
if [[ -z "${ALTER_VERBOSE}" ]]; then
exit 0
else
echo $MESSAGE
fi
}

To:

function msg() {
   MESSAGE=$1
   if [[ -z "${ALTER_VERBOSE}" ]]; then
      return
   else
      echo $MESSAGE
   fi
 }

@tuaris
Copy link

tuaris commented Aug 28, 2024

What would be the downside/danger of looking at grep's exit code instead of comparing strings?

if grep -q $HOSTNAME /etc/hosts; then 
  # Entry already exists
else
   # Add in the entry
fi

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