Skip to content

Instantly share code, notes, and snippets.

@dfeyer
Forked from nddrylliog/host-manager
Created November 16, 2011 10:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfeyer/1369760 to your computer and use it in GitHub Desktop.
Save dfeyer/1369760 to your computer and use it in GitHub Desktop.
A command-line utility to manage the /etc/hosts file.
#!/bin/bash
# Idea and interface taken from https://github.com/macmade/host-manager
path="/etc/hosts"
addusage="Usage: `basename $0` --add host address"
remusage="Usage: `basename $0` --remove host"
listusage="Usage: `basename $0` --list [127.]"
case "$1" in
--add)
if [ $# -eq 3 ]; then
if [[ -n $(grep "^$3.*[^A-Za-z0-9\.]$2$" ${path}) ]]; then
echo "Duplicate address/host combination, ${path} unchanged."
else
printf "$3\t$2\n" >> ${path}
fi
else
echo $addusage;
fi
;;
--remove)
if [ $# -eq 2 ]; then
sed -i '' "s/^[^#].*[^A-Za-z0-9\.]$2$//g;/^$/d" ${path}
else
echo $remusage;
fi
;;
--list)
if [ $# -eq 2 ]; then
grep "^$2" ${path}
else
cat ${path} | grep -v "^#"
fi
;;
*)
echo $addusage;
echo $remusage;
echo $listusage;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment