Created
October 1, 2015 13:03
-
-
Save gibatronic/8a2346263f2f5e8d7ca5 to your computer and use it in GitHub Desktop.
parse options in shell script
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
#!/usr/bin/env bash | |
ACTION= | |
OPTION_A='undefined' | |
OPTION_B='undefined' | |
OPTIONS=("$@") | |
LENGTH=${#OPTIONS[@]} | |
main() { | |
echo " Action: $ACTION" | |
echo "Option A: $OPTION_A" | |
echo "Option B: $OPTION_B" | |
} | |
usage() { | |
echo '' | |
echo ' Usage:' | |
echo " $(basename $0) [options] <action>" | |
echo '' | |
echo ' Options:' | |
echo " -a --option-a the option A" | |
echo " -b --option-b the option B" | |
echo '' | |
} | |
if [ $LENGTH = 0 ]; then | |
usage | |
exit 1 | |
fi | |
while (("$#")); do | |
OPTION=${OPTIONS[$LENGTH - $#]} | |
case "$OPTION" in | |
-a|--option-a) | |
shift | |
OPTION_A=${OPTIONS[$LENGTH - $#]} | |
;; | |
--option-a=*) | |
OPTION_A=${OPTION/--option-a=} | |
;; | |
-b|--option-b) | |
shift | |
OPTION_B=${OPTIONS[$LENGTH - $#]} | |
;; | |
--option-b=*) | |
OPTION_B=${OPTION/--option-b=} | |
;; | |
*) | |
ACTION=${OPTION} | |
esac | |
shift | |
done | |
if [ -z "${ACTION}" ]; then | |
usage | |
exit 1 | |
fi | |
main && exit 0 || exit 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment