Reputation: 563
I have came across a below code snippet and not sure exactly what's the purpose of -? in the while loop. I searched across multiple sites and forums for this parameter but couldn't get any exact answer.
Any inputs please, thank you.
while [[ $1 = -? ]]; do
case $1 in
-a) a1=alligator ;;
-b) a2=bear ;;
-c) a3=cougar ;;
esac
shift
Upvotes: 0
Views: 39
Reputation: 246774
In ksh, within double brackets, the =
and ==
operators are for pattern matching: [[ string = pattern ]]
[1]
These are shell pathname expansion patterns. ?
will match any single character.
So what you're testing for is if $1
matches a hyphen followed by any single character. In other words, does the first positional parameter look like an option string.
[1] -- to perform string equality checking, your pattern either contains no special globbing characters, or such characters are quoted or escaped.
IMO, a more robust way to do option parsing is with the getopts
builtin:
while getopts :abc opt; do
case $opt in
a) a1=alligator ;;
b) a2=bear ;;
c) a3=cougar ;;
:) print -u2 "error: missing required argument for -$OPTARG" ;;
?) print -u2 "unknown option: -$OPTARG" ;;
esac
done
shift $((OPTIND - 1))
Upvotes: 2