-
-
Save wonjun27/eced692d6cd4b0c1a788245b97cdac21 to your computer and use it in GitHub Desktop.
Bash Script functions to Manage /etc/hosts file for adding/removing hostnames.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# remove specified host from /etc/hosts | |
function removehost() { | |
if [[ "$1" ]] | |
then | |
HOSTNAME=$1 | |
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 | |
else | |
echo "Error: missing required parameters." | |
echo "Usage: " | |
echo " removehost domain" | |
fi | |
} | |
#add new ip host pair to /etc/hosts | |
function addhost() { | |
if [[ "$1" && "$2" ]] | |
then | |
IP=$1 | |
HOSTNAME=$2 | |
if [ -n "$(grep $HOSTNAME /etc/hosts)" ] | |
then | |
echo "$HOSTNAME already exists:"; | |
echo $(grep $HOSTNAME /etc/hosts); | |
else | |
echo "Adding $HOSTNAME to your /etc/hosts"; | |
printf "%s\t%s\n" "$IP" "$HOSTNAME" | sudo tee -a /etc/hosts > /dev/null; | |
if [ -n "$(grep $HOSTNAME /etc/hosts)" ] | |
then | |
echo "$HOSTNAME was added succesfully:"; | |
echo $(grep $HOSTNAME /etc/hosts); | |
else | |
echo "Failed to Add $HOSTNAME, Try again!"; | |
fi | |
fi | |
else | |
echo "Error: missing required parameters." | |
echo "Usage: " | |
echo " addhost ip domain" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment