Skip to content

Instantly share code, notes, and snippets.

@CesarChaMal
Forked from irazasyed/manage-etc-hosts.sh
Created July 4, 2020 14:59
Show Gist options
  • Select an option

  • Save CesarChaMal/8f323f5ab65361145dbdbcadfabaa820 to your computer and use it in GitHub Desktop.

Select an option

Save CesarChaMal/8f323f5ab65361145dbdbcadfabaa820 to your computer and use it in GitHub Desktop.

Revisions

  1. @irazasyed irazasyed created this gist Mar 7, 2015.
    39 changes: 39 additions & 0 deletions manage-etc-hosts.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    #!/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
    }