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
}
@nielsvanzon
Copy link

changing the console from sh to bash worked for me like a charm in ubuntu 20.04

#!/bin/bash

# run:
# ./manage-etc-hosts.sh add 10.20.1.2 test.com
# ./manage-etc-hosts.sh remove 10.20.1.2 test.com

# PATH TO YOUR HOSTS FILE
ETC_HOSTS=/etc/hosts


function remove() {
    # IP to add/remove.
    IP=$1
    # Hostname to add/remove.
    HOSTNAME=$2
    HOSTS_LINE="$IP[[:space:]]$HOSTNAME"
    if [ -n "$(grep -P $HOSTS_LINE $ETC_HOSTS)" ]
    then
        echo "$HOSTS_LINE Found in your $ETC_HOSTS, Removing now...";
        sudo sed -i".bak" "/$HOSTS_LINE/d" $ETC_HOSTS
    else
        echo "$HOSTS_LINE was not found in your $ETC_HOSTS";
    fi
}

function add() {
    IP=$1
    HOSTNAME=$2
    HOSTS_LINE="$IP[[:space:]]$HOSTNAME"
    line_content=$( printf "%s\t%s\n" "$IP" "$HOSTNAME" )
    if [ -n "$(grep -P $HOSTS_LINE $ETC_HOSTS)" ]
        then
            echo "$line_content already exists : $(grep $HOSTNAME $ETC_HOSTS)"
        else
            echo "Adding $
```line_content to your $ETC_HOSTS";
            sudo -- sh -c -e "echo '$line_content' >> /etc/hosts";

            if [ -n "$(grep -P $HOSTNAME $ETC_HOSTS)" ]
                then
                    echo "$line_content was added succesfully";
                else
                    echo "Failed to Add $line_content, Try again!";
            fi
    fi
}

$@

I think you made a typo here
echo "Adding $ ```line_content to your $ETC_HOSTS";

should be this I guess:
echo "Adding $line_content to your $ETC_HOSTS";

@Ran-Xing
Copy link

how do we solve the problem of password prompt. Every time i run the script it ask for password. I dont want to enter the password manually. Has any one solved this problem???

chmod 666 /etc/hosts

@ceelian
Copy link

ceelian commented Mar 25, 2023

Thanks for the scripts. I tried them but these scripts are adding new lines even though the same IP already exists. This does not conform with the /etc/hosts format and can cause issues.

Therefore I created a script that adds the hostname to the IP address line if the IP already exists in the hosts file. Only if it doesn't exist, a new line will be added. Gist is here: https://gist.github.com/ceelian/0c293cf0e10c924a2124e2c9fa3805a9

@kucerarichard
Copy link

Thanks for the scripts. I tried them but these scripts are adding new lines even though the same IP already exists. This does not conform with the /etc/hosts format and can cause issues.

Therefore I created a script that adds the hostname to the IP address line if the IP already exists in the hosts file. Only if it doesn't exist, a new line will be added. Gist is here: https://gist.github.com/ceelian/0c293cf0e10c924a2124e2c9fa3805a9

this script does't remove, we need that. thanks!

For example I can't use experimental podman on an old host, so I have to build and use httperf directly and try to add host aliases without being too cumbersome:

add_host_alias "host:ip" && httperf ... && remove_host_alias "host:ip"

@kucerarichard
Copy link

kucerarichard commented Sep 13, 2023

Productionized for my use of httperf. Tested a bit.

#!/bin/bash

# Synopsis:
# ./alterhost.sh add-host test.com:1.2.3.4
# ./alterhost.sh add-host 'test.com:1.2.3.4;test2.com:2.3.4.5;test3.com:3.4.5.6'
# ./alterhost.sh del-host test.com:1.2.3.4
# ALTER_VERBOSE=t ./alterhost.sh del-host test.com:1.2.3.4

if test $# -lt 2 ; then
echo "USAGE: alterhost <verb> '<name:ip;name:ip;name:ip...>' "
echo 'EX: ./alterhost.sh add-host test.com:1.2.3.4'
echo "EX: ./alterhost.sh add-host 'test.com:1.2.3.4;test2.com:2.3.4.5;test3.com:3.4.5.6'"
echo 'EX: ./alterhost.sh del-host test.com:1.2.3.4'
echo 'EX: ALTER_VERBOSE=t ./alterhost.sh del-host test.com:1.2.3.4'
echo "EX: ./alterhost.sh add-host 'www.test.org:2.3.5.6' ;  httperf --server www.test.org --uri /LICENSE.txt --num-conns 10 --rate 10 --timeout 10 --hog --ssl ; ./alterhost.sh del-host 'www.test.org:2.3.5.6'"
exit -1
fi

# PATH TO YOUR HOSTS FILE
#ETC_HOSTS=/etc/hosts
ETC_HOSTS=./test_etc_hosts

[ ! -f $ETC_HOSTS.bak2 ] && cp -p $ETC_HOSTS $ETC_HOSTS.bak2

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

function del-host() {
  for i in $(echo $1 | sed -e 's/;/\n/g'); do
    readarray -t HOSTIP < <(echo $i | awk -F':' '{print $1; print $2}')
    IP=${HOSTIP[1]}
    HOSTNAME=${HOSTIP[0]}
    HOSTS_LINE="$IP[[:space:]]$HOSTNAME"
    if [ -n "$(grep -P $HOSTS_LINE $ETC_HOSTS)" ]
    then
        msg "${HOSTIP[*]} Found in your $ETC_HOSTS, Removing now..."
        sudo sed -i".bak" "/$HOSTS_LINE/d" $ETC_HOSTS
    else
        msg "${HOSTIP[*]} was not found in your $ETC_HOSTS"
    fi
  done
}

function add-host() {

  for i in $(echo $1 | sed -e 's/;/\n/g'); do
    readarray -t HOSTIP < <(echo $i | awk -F':' '{print $1; print $2}')
    IP=${HOSTIP[1]}
    HOSTNAME=${HOSTIP[0]}
    HOSTS_LINE="$IP[[:space:]]$HOSTNAME"
    line_content=$( printf "%s\t%s\n" "$IP" "$HOSTNAME" )
    if [ -n "$(grep -P $HOSTS_LINE $ETC_HOSTS)" ]
        then
            msg "$line_content already exists : $(grep $HOSTNAME $ETC_HOSTS)"
        else
            msg "Adding $line_content to your $ETC_HOSTS";
            sudo -- sh -c -e "echo '$line_content' >> $ETC_HOSTS";

            if [ -n "$(grep -P $HOSTNAME $ETC_HOSTS)" ]
                then
                    msg "$line_content was added succesfully";
                else
                    msg "Failed to Add $line_content, better take a look!";
                    exit -1
            fi
    fi
  done
}

$@

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