Technotes

Technotes for future me

Hostfile

#!/bin/bash
HOSTNAME=blaataap.com
IP="127.0.0.1"
ETC_HOSTS=/etc/hosts

removehost () {

    # shellcheck disable=SC2143
    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
}

addhost () {

    HOSTS_LINE="$IP    $HOSTNAME"
    # shellcheck disable=SC2143
    if [ -n "$(grep "$HOSTNAME" /etc/hosts)" ]
        then
            echo "$HOSTNAME already exists : $(grep "$HOSTNAME" "$ETC_HOSTS")"
        else
            echo "Adding $HOSTNAME to your $ETC_HOSTS"
            echo "$HOSTS_LINE"
            echo "$HOSTS_LINE" >> /etc/hosts

            if [ -n "$(grep "$HOSTNAME" /etc/hosts)" ]
                then
                    # echo "$HOSTNAME was added succesfully \n $(grep $HOSTNAME /etc/hosts)"
                    printf "%s was added succesfully \n$(grep "$HOSTNAME" /etc/hosts) \n" "$HOSTNAME"
                else
                    echo "Failed to Add $HOSTNAME, Try again!"
            fi
    fi
}


removehost
addhost
Last updated on 31 Jan 2021
Published on 16 Dec 2019
Edit on GitHub