help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Setting variable with getopts


From: Dennis Williamson
Subject: Re: Setting variable with getopts
Date: Mon, 9 Aug 2021 11:50:32 -0500

On Mon, Aug 9, 2021, 11:37 AM Dennis Williamson <dennistwilliamson@gmail.com>
wrote:

>
>
> On Mon, Aug 9, 2021, 11:02 AM hancooper <hancooper@protonmail.com> wrote:
>
>> ‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
>> On Monday, August 9, 2021 4:00 PM, hancooper <hancooper@protonmail.com>
>> wrote:
>>
>>
>> Add
>> local OPTIND
>> at the top of your function.
>>
>>
>>
>> It is peculiar to me that I do not need to define
>> local OPTARG
>> as well
>>
>>
>
> For getopts an option either requires an argument or not. There is no
> support for optional arguments although your code can handle the missing
> argument error which is indicated by a colon as the option and OPTARG is
> set to the option. You would need to set the first character of the
> optstring to a colon so that error processing is silent.. If the option is
> to have optional arguments you would process the case without an argument
> specially.
>
> status ()
> {
>
> local vrb=1
> local shortopts=":Vuhp:"
>
> while getopts $shortopts arg; do
>   case $arg in
>
>   # section omitted
>
>     ("p")
>       p="$OPTARG"
>       printf '%s\n' "p, arg: $arg ; OPTARG: $OPTARG"
>       ;;
>     (:)
>      case $OPTARG in
>         (j) echo "this option has an optional argument, handle no arg
> here" ;;
>         (*)
>               echo "Current argument value, OPTARG: -$OPTARG" >&2
>               echo "Must supply an argument to -$OPTARG" >&2
>               ;;
>         esac
>
> # section omitted
>
>   esac
> done
> shift "$OPTIND"
>
> echo "p: $p"
>
> }
>

However if any option follow the one with an optional and not-present
argument, it will be considered as the argument instead. You would need to
handle that specially. It gets hairy quickly.

>


reply via email to

[Prev in Thread] Current Thread [Next in Thread]