$ cat common.sh
function get_options {
while getopts ":ab:" optionName
do
echo "get_options: OPTARG: $OPTARG, optionName: $optionName"
done
}
$ cat a.sh
#!/bin/bash
. ./common.sh
function get_local_options {
while getopts ":xy:" optionName; do
case $optionName in
x|y)
echo "get_local_options: OPTARG: $OPTARG, optionName: $optionName"
last=$OPTIND;;
*) echo "get_local_options, done with $optionName"
break;;
esac;
done
}
last=1
get_local_options $*
shift $(($last - 1))
OPTIND=1
get_options $*
$ ./a.sh -x -y foo -a -b bar
get_local_options: OPTARG: , optionName: x
get_local_options: OPTARG: foo, optionName: y
get_local_options, done with ?
get_options: OPTARG: , optionName: a
get_options: OPTARG: bar, optionName: b
$ ./a.sh -a -b bar
get_local_options, done with ?
get_options: OPTARG: , optionName: a
get_options: OPTARG: bar, optionName: b
#!/bin/bash
UNHANDLED=()
function getxy {
while ((OPTIND<=$#)); do
if getopts ":xy:" opt; then
case $opt in
x|y) echo "getxy opt=$<$opt> OPTARG=<$OPTARG>";;
*) UNHANDLED+=(-$OPTARG);;
esac
else
UNHANDLED+=(${!OPTIND})
let OPTIND++
fi
done
}
function getab {
while getopts ":ab:" opt; do
case $opt in
a|b) echo "getab opt=$<$opt> OPTARG=<$OPTARG>";;
*) echo "getab * opt=<$opt> OPTARG=<$OPTARG>";;
esac
done
}
echo "--- getxy ---"
OPTIND=1
getxy "$@"
# now we reset OPTIND and parse again using the UNHANDLED array
echo "--- getab ---"
OPTIND=1
set -- "${UNHANDLED[@]}"
getab "$@"
# now we get remaining args
shift $((OPTIND-1))
for arg; do
echo "arg=<$arg>"
done