Created
January 26, 2016 08:43
-
-
Save thefekete/fb9e29f07bd207f62cb4 to your computer and use it in GitHub Desktop.
Bash script template for options parsing
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 | |
# see http://stackoverflow.com/a/14203146 for more on this | |
set -e | |
set -u | |
################### | |
# Option Defailts # | |
################### | |
opt="option default" | |
flag=false | |
verbose=0 | |
################### | |
# Version & Usage # | |
################### | |
VERSION="0.0.0" | |
USAGE=" | |
$(basename $0) version $VERSION | |
usage: | |
$(basename $0) [options] arg1 [arg2 ...] | |
options: | |
-o, --opt val set opt to val [$opt] | |
-f, --flag enable flag | |
-v, --verbose increase verbosity | |
-h, --help print this message and exit | |
-- options terminator | |
DESCRIPTION | |
" | |
################# | |
# Parse Options # | |
################# | |
while [[ $1 == -* ]]; do | |
case $1 in | |
-o|--opt) | |
opt="$2" | |
shift # past value | |
;; | |
-f|--flag) | |
flag=true | |
# do not shift again! | |
;; | |
-v|--verbose) | |
((verbose+=1)) | |
# do not shift again! | |
;; | |
-h|--help) | |
echo "$USAGE" | |
exit | |
;; | |
--) | |
shift | |
break | |
;; | |
*) | |
>&2 echo "$(basename $0): unknown option $1" \ | |
"(run '$(basename $0) --help' for available options)" | |
exit 1 | |
esac | |
shift | |
done | |
# all options have been shifted out, so just arguments are left in $@ | |
############### | |
# Main Script # | |
############### | |
echo "opt = $opt" | |
if [ "$flag" = true ]; then | |
echo "flag = enabled ($flag)" | |
else | |
echo "flag = disabled ($flag)" | |
fi | |
echo "verbose = $verbose" | |
i=0 | |
for arg in "$@"; do | |
echo "arg $i = $arg" | |
((i+=1)) | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment