I am re-learning getopt
with a tiny script in bash, but the second parameters fall into default branch of case
.
#! /bin/bash
LONG_OPTION_LIST=(
"arg-a"
"arg-b:"
"arg-c:"
)
SORT_OPTION_LIST=(
"a"
"b:"
"c:"
)
Read the parameters
opts=$(getopt -q
--longoptions "$(printf "%s," "${LONG_OPTION_LIST[@]}")"
--name "$(basename "$0")"
--options "$(printf "%s" "${SORT_OPTION_LIST[@]}")"
-- "$@"
)
eval set -- "$opts"
echo "##$1##"
echo "##$2##"
echo "##$3##"
echo "##$4##"
echo "##$5##"
echo "#########"
argA=0
It it is same a queue (process the head) because $1 and $2
for arg
do
echo $1
echo $2
echo "--------"
case "$arg" in
--arg-a | -a)
argA=1
shift 1
;;
--arg-b | -b)
argB=$2
shift 2
;;
--arg-c | -c)
argC=$2
shift 2
;;
*)
echo "###$1###"
echo "break"
echo "_________"
break
;;
esac
done
echo "argA $argA"
echo "argB $argB"
echo "argC $argC"
And some examples:
user@pc:/tmp$ ./test.bash -a
##-a##
##--##
####
####
####
#########
-a
--
--------
--
###--###
break
_________
argA 1
argB
argC
user@pc:/tmp$ ./test.bash -b 111
##-b##
##111##
##--##
#########
-b
111
--
###--###
break
_________
argA 0
argB 111
argC
user@pc:/tmp$ ./test.bash -a -b 111
##-a##
##-b##
##111##
##--##
#########
-a
-b
-b
111
--
###--###
break
_________
argA 1
argB 111
argC
user@pc:/tmp$ ./test.bash -b 111 -a
##-b##
##111##
##-a##
##--##
#########
-b
111
-a
###-a###
break
_________
argA 0
argB 111
argC
$1
and$2
insidefor arg; do
like that, they'll just have whatever values they had before the loop. E.g.set -- aa bb cc; for x; do echo $1; done
givesaa
three times. Not thatshift
works either,set -- aa bb cc; for x; do echo $x; shift; done
givesaa
,bb
andcc
, without the shift affecting the loop. – ilkkachu Mar 21 '22 at 13:52