Created
November 15, 2011 22:06
-
-
Save nddrylliog/1368532 to your computer and use it in GitHub Desktop.
A command-line utility to manage the /etc/hosts file.
This file contains 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
#!/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 |
@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
Good stuff, will definitely find use for this. Would getopt be overkill here though, if only for the sake of brevity on the CLI?