Created
October 10, 2014 10:36
-
-
Save killwing/5c50b25321648d6c1f17 to your computer and use it in GitHub Desktop.
cmd line options parser
This file contains hidden or 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 | |
# for optional arguments: short - there can't be any spaces between the option and the argument | |
# long - the argument can only be passed by "=" | |
# parse options | |
OPTIONS=$(getopt -o o::r:n -l optional::,required:,none -n "$0" -- "$@") | |
# check result | |
[ $? -ne 0 ] && exit 1 | |
# set parsed options | |
eval set -- "$OPTIONS" | |
optional="" | |
required="" | |
none=0 | |
# process | |
while true; do | |
case "$1" in | |
-o|--optional) | |
case "$2" in | |
"") optional='default' | |
shift 2 ;; | |
*) optional=$2 | |
shift 2 ;; | |
esac ;; | |
-r|--required) | |
required=$2 | |
shift 2 ;; | |
-n|--none) | |
none=1 | |
shift ;; | |
--) shift | |
break ;; | |
*) echo "error!" | |
exit 1 ;; | |
esac | |
done | |
echo "none = $none" | |
echo "required = $required" | |
echo "optional = $optional" | |
echo "left = $@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://www.bahmanm.com/blogs/command-line-options-how-to-parse-in-bash-using-getopt