Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bash Script functions to Manage /etc/hosts file for adding/removing hostnames.
# 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" ]]
then
HOSTNAME=$1
IP="${2:-127.0.0.1}"
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 domain [IP]"
fi
}
@KevinDanikowski
Copy link

KevinDanikowski commented Jun 12, 2018

please describe how to use if possible

Loading

@bitmvr
Copy link

bitmvr commented Jul 11, 2018

@KevinDanikowski,

These are just functions that can be added to the .bashrc (or some file another file that is sourced in .bashrc). Once they are added, you need source .bashrc for them to get picked up. The easiest way to do this is do the following...

source $HOME/.bashrc

That's it. Happy hacking!

Loading

@Fuxy22
Copy link
Author

Fuxy22 commented Aug 20, 2021

Yep. These are just helper function i used mostly in homestead or other virtual machines or docker containers to edit /etc/hosts so a certain domain name can be pointed to a certain IP address.

Just create a ~/.bash_aliases file and make sure it is sourced in your ~/.bashrc file and either source that file or just close you console and open a new one.

Loading

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