I wanted to share what I made for parsing options. Some of my needs were not fulfilled (like suboption management, var args, optional args etc.) by the answers here so I had to come up with this: https://github.com/MihirLuthra/bash_option_parser
This supports:
- Suboption parsing
- Alias names for options
- Optional args
- Variable args
- Printing usage and errors
fruit <fruit-name> ...
[-e|—-eat|—-chew]
[-c|--cut <how> <why>]
<command> [<args>]
fruit <fruit-name> ...
[-e|—-eat|—-chew]
[-c|--cut <how> <why>]
<command> [<args>]
retval=$?
if [ $retval -ne 0 ]; then
# this will manage error messages if
# insufficient or extra args are supplied
option_parser_error_msg "$retval"
'OPTIONS' # This will print the usage
print_usage 'fruit'
exit 1
fi
if [ -n "${OPTIONS[-c]}" ]
then
echo "-c was passed"
# args can be accessed in a 2D-array-like format
echo "Arg1 to -c = ${ARGS[-c,0]}"
echo "Arg2 to -c = ${ARGS[-c,1]}"
fi
For a suboption, like apple whose usage looks like:
fruit apple ...
[—-eat-apple|—-chew-apple]
[-p|—-peel <how>]
We can check if it was passed and parse it as follows:
if [ -n "${OPTION[apple]}" ]
then
shift_count=${OPTION[apple]}
parse_options_detailed \
',' 'OPTIONS_APPLE' 'ARG_CNT_APPLE' 'ARGS_APPLE' \
"$shift_cnt" ';' '--' 'error_opt' \
\
'apple' '...' \
'—-eat-apple' , '—-chew-apple' '0' \
'-p' , '—-peel' '1' \
';' \
"$@"
fi
Suboption parsing iscan also be done by passing $shift_count to parse_options_detailed which makes it start parsing after shifting args to reach args of suboption. It is demonstrated in this example.