Last active
July 5, 2016 14:48
-
-
Save pgassmann/150119a64d23f82b0e479fb45c4bdd12 to your computer and use it in GitHub Desktop.
bash tool boilerplate
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 | |
# Bash script with subcommands and options | |
# Licence: MIT | |
# Based on | |
# - http://stackoverflow.com/questions/13638248/sub-commands-with-bash | |
# - http://wiki.bash-hackers.org/howto/getopts_tutorial | |
help() { | |
echo "Help: valid commands: install, apply, setup, help" >&2 | |
} | |
install() { | |
while getopts :m: opt "$@"; do | |
case $opt in | |
m) | |
echo "Set install mode: $OPTARG" >&2 | |
;; | |
\?) | |
echo "Invalid install option: -$OPTARG" >&2 | |
exit 1 | |
;; | |
:) | |
echo "Installation mode -$OPTARG requires an argument." >&2 | |
exit 1 | |
;; | |
esac | |
done | |
echo "installing" | |
} | |
apply() { | |
shift $((OPTIND - 1)) | |
echo "run apply $@" | |
} | |
setup() { | |
shift $((OPTIND - 1)) | |
install | |
apply "$@" | |
} | |
# demo | |
args() { | |
printf "%s" options: | |
while getopts a:b:c:d:e:f:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z: OPTION "$@"; do | |
printf " -%s '%s'" $OPTION $OPTARG | |
done | |
shift $((OPTIND - 1)) | |
printf "\narg: '%s'" "$@" | |
echo | |
} | |
if [[ $1 =~ ^(install|apply|help|args)$ ]]; then | |
"$@" | |
else | |
help | |
echo "first arg '$1' is not a valid command, passing all options to setup" >&2 | |
setup "$@" | |
# echo "Invalid subcommand $1" >&2 | |
# exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment