Skip to content

Instantly share code, notes, and snippets.

@morenoh149
Created November 14, 2022 16:04
Show Gist options
  • Save morenoh149/79e7e9ef3c0d7436b25daaa8f8594e83 to your computer and use it in GitHub Desktop.
Save morenoh149/79e7e9ef3c0d7436b25daaa8f8594e83 to your computer and use it in GitHub Desktop.
bash script for add/removing host in /etc/hosts
#!/bin/bash
hosts() {
VALID_COMMANDS=("help" "show" "samplefile" "activate" "deactivate")
NO_ARG_COMMANDS=("help" "show" "samplefile")
GREEN='\033[0;32m';
RED='\033[0;31m';
NOCOLOR='\033[0m';
read -r -d '' SAMPLE_ETC_HOSTS_FILE <<HEREDOC
#
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
#%%%my-project.HOSTS%%%
127.0.0.1 foo.myproject.com
#%%%ALWAYS_ON%%%
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
# Added by Docker Desktop
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section
HEREDOC
read -r -d '' HELP_MESSAGE <<HEREDOC
Usage:
hosts help
hosts show
hosts samplefile
hosts activate [SECTION]
hosts deactivate [SECTION]
HEREDOC
if [[ ! " ${VALID_COMMANDS[*]} " =~ " $1 " ]]
then
printf "${RED}Valid Commands are: ${VALID_COMMANDS[*]}${NOCOLOR}\n\n";
return;
fi
if [[ ! " ${NO_ARG_COMMANDS[*]} " =~ " $1 " && ! "$2" ]]
then
printf "${RED}You must provide the name of the section to activate/deactivate${NOCOLOR}\n\n";
return;
fi
if [[ $1 == "help" ]]
then
echo "${HELP_MESSAGE}";
return;
elif [[ $1 == "show" ]]
then
printf "${GREEN}Contents of '/etc/hosts'${NOCOLOR}\n\n";
sudo cat /etc/hosts;
return;
elif [[ $1 == "samplefile" ]]
then
echo "${SAMPLE_ETC_HOSTS_FILE}";
return;
elif [[ $1 == "activate" ]]
then
sudo sed -i'.original' -e '/#%%%'"${2}"'.HOSTS/,/#%%%/s/^#\([^%]\)/\1/g' /etc/hosts
printf "${GREEN}Activated $2 section of /etc/hosts file${NOCOLOR}\n\n";
return;
elif [[ $1 == "deactivate" ]]
then
sudo sed -i'.original' -e '/#%%%'"${2}"'.HOSTS/,/#%%%/s/^\([^#]\)/#\1/g' /etc/hosts
printf "${GREEN}Deactivated $2 section of /etc/hosts file${NOCOLOR}\n\n";
return;
fi
}
@morenoh149
Copy link
Author

you can enable this function in your shell by running source ./hosts.sh

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