home | list info | list archive | date index | thread index

curious about official behaviour of POSIX "getopts"

  i was messing around with "getopts" and wanted to document several
examples of encouraged usage, and one of the examples is here (note
the leading ":" in the getopts string, which overrides normal error
processing):

===== start

#!/bin/bash --posix

aflag=
bflag=
cflag=

while getopts :ab:c name
do
        case $name in
        a)      aflag=1
                ;;

        b)      bflag=1
                bval="$OPTARG"
                ;;

        c)      cflag=1
                ;;

        :)      echo "${OPTARG} requires an argument"
                ;;

        \?)     echo "Unknown option $OPTARG"
                ;;
        esac
done

if [ ! -z "$aflag" ]; then
        printf "Option -a specified\n"
fi

if [ ! -z "$bflag" ]; then
        printf 'Option -b "%s" specified\n' "$bval"
fi

if [ ! -z "$cflag" ]; then
        printf "Option -c specified\n'"
fi

shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"

===== end

  clearly, the above shows that options "-a" and "-c" do not take an
argument, while "-b" does. so i tested it, and was surprised to see:

$ ./1.sh -a -b -c
Option -a specified
Option -b "-c" specified
Remaining arguments are:
$

  in short, rather than being told that "-b" has a missing argument,
it simply used the argument "-c" for that. i did *not* see that
coming. is that normal behaviour? it seems somehow counter-intuitive.

rday

To unsubscribe send a blank message to linux+unsubscribe [ at ] linux-ottawa [ dot ] org
To get help send a blank message to linux+help [ at ] linux-ottawa [ dot ] org
To visit the archives: https://lists.linux-ottawa.org

message navigation