Skip to content

Instantly share code, notes, and snippets.

@jontey
Forked from alrik11es/manage-etc-hosts.sh
Created December 2, 2019 04:47
Show Gist options
  • Save jontey/4f9c6ccdfc06b043726e64c8d976490f to your computer and use it in GitHub Desktop.
Save jontey/4f9c6ccdfc06b043726e64c8d976490f to your computer and use it in GitHub Desktop.
Bash Script to Manage /etc/hosts file for adding/removing hostnames.
#!/usr/bin/env bash
# sudo apt-get install -y nscd
set -eu
if [ "$EUID" -ne 0 ]
then echo "Please run as root"
exit
fi
# PATH TO YOUR HOSTS FILE
: ${ETC_HOSTS="/etc/hosts"}
# DEFAULT IP FOR HOSTNAME
DEFAULT_IP="127.0.0.1"
VERBOSE=false
function remove() {
local HOSTNAME=$1
local HOST_REGEX="\(\s\+\)${HOSTNAME}\s*$"
local HOST_LINE="$(grep -e "${HOST_REGEX}" ${ETC_HOSTS})"
if [ -n "${HOST_LINE}" ]; then
[ ${VERBOSE} == true ] && echo "${HOSTNAME} Found in your ${ETC_HOSTS}, Removing now..."
sed -i -e "s/${HOST_REGEX}/\1/g" -e "/^[^#][0-9\.]\+\s\+$/d" ${ETC_HOSTS}
else
[ ${VERBOSE} == true ] && echo "${HOSTNAME} was not found in your ${ETC_HOSTS}";
fi
}
function add() {
local HOSTNAME=$1
local IP=${2:-${DEFAULT_IP}}
local HOST_REGEX="\(\s\+\)${HOSTNAME}\s*$"
local HOST_LINE="$(grep -e "${HOST_REGEX}" ${ETC_HOSTS})"
if [ -n "${HOST_LINE}" ]; then
[ ${VERBOSE} == true ] && echo "${HOSTNAME} already exists : ${HOST_LINE}"
else
[ ${VERBOSE} == true ] && echo "Adding ${HOSTNAME} to your ${ETC_HOSTS}";
echo -e "${IP}\t${HOSTNAME}" >> ${ETC_HOSTS}
[ ${VERBOSE} == true ] && echo -e "${HOSTNAME} was added succesfully \n ${HOST_LINE}";
nscd -i hosts
fi
}
# Execute
$@
@jontey
Copy link
Author

jontey commented Dec 2, 2019

sudo wget -O /usr/local/bin/hosts https://gist.github.com/jontey/4f9c6ccdfc06b043726e64c8d976490f/raw/44e982b5f4579c083518351cb7c19e80ed84dce7/hosts
sudo chmod +x /usr/local/bin/hosts

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