Skip to content

Instantly share code, notes, and snippets.

@nddrylliog
Created November 15, 2011 22:06
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save nddrylliog/1368532 to your computer and use it in GitHub Desktop.
Save nddrylliog/1368532 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"
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 '' -e "s/^[^#].*[^A-Za-z0-9\.]$2$//g" -e "/^$/ d" ${path}
else
echo $remusage;
fi
;;
*)
echo $addusage;
echo $remusage;
esac
@nddrylliog
Copy link
Author

@jdp Interesting, I didn't know getopts was also a bash thing (I only knew about the C lib). I have just looked into it, but it does indeed seem like overkill because we never use more than one dash-argument at once, and those don't really have values, more like positional parameters.

I'm not against it, but I don't see a more elegant way to parse arguments right now (we could use local variables to increase readability, which I have omitted of brevity, probably a wrong move on my account)

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