anybody know a nice way to parse long input parameters such as --path /dir1/dir2/ (see below). Now I have more than 10 input parameters and it's confusing having parameters like -q something, I would prefer longer ones
case $OPTKEY in
--path) M_PATH=$OPTARG ;;
-s) S_PATH=$OPTARG ;;
done
I am using cygwin and it seems getopt is not available (only getopts)
cheers
it has been a while since I have tried to parse command line arguments
made of both short and long options. There are many ways to do so but
not as many of them handle switch clustering in a flawlessly way. Here
is a snippet of code that illustrates my point. It is, however, far from
being straightforward (getopts is) since it requires to do the parsing
by hand. At last, the sample uses builtins commands only so the parsing
is expected to be optimal.
At parsing time, OPTARG holds the last expected option argument.
while :; do
case "$#" in 0) break; esac; OPTSTR="$1"
case "$OPTSTR" in --) break ;;
--flag_1) OPTSTR=-f1 ;;
--flag_2) OPTSTR=-f2 ;;
--flag_3) OPTSTR=-f3 ;;
--optarg_1) OPTSTR=-o1 ;;
--optarg_2) OPTSTR=-o2 ;;
esac
case "$OPTSTR" in
-*) OPTSTR="${OPTSTR#-}"
while :; do
case "${#OPTSTR}" in 0) break; esac
ARGSTR="${OPTSTR#?}"; OPTSTR="${OPTSTR%${ARGSTR}}"
case "$OPTSTR" in
o1) OPTARG="$(get_arg "$2")" && shift; case "$?" in 1) exit 65; esac
logger "-o1/--optarg_1 argument is $OPTARG";;
o2) OPTARG="$(get_arg "$2")" && shift; case "$?" in 1) exit 65; esac
logger "-o2/--optarg_2 argument is $OPTARG";;
f1) logger "FLAG_1 is set";;
f2) logger "FLAG_2 is set";;
f3) logger "FLAG_3 is set";;
*) logger "--> unrecognized option -${OPTSTR}" >&2 && exit 65 ;;
esac
case "$OPTSTR" in o1*|o2*) break; esac
OPTSTR="$ARGSTR"
done
esac
shift
done