[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Setting variable with getopts
From: |
hancooper |
Subject: |
Setting variable with getopts |
Date: |
Mon, 09 Aug 2021 16:57:20 +0000 |
I would like to have
myfunc -v 8 # sets vb to 8
myfunc -v # sets vb to default 1
If it gets hairy quickly, how does Gnu Bash not provide a decent way to handle
function arguments?
Basically, accept short and long options, and options with optional arguments
in an easy way for users
of bash. That would be much smarter than the current situation.
‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Monday, August 9, 2021 4:50 PM, Dennis Williamson
<dennistwilliamson@gmail.com> wrote:
> 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.
>
>>
- Setting variable with getopts, hancooper, 2021/08/09
- Setting variable with getopts, hancooper, 2021/08/09
- Re: Setting variable with getopts, Dennis Williamson, 2021/08/09
- Re: Setting variable with getopts, hancooper, 2021/08/09
- Setting variable with getopts, hancooper, 2021/08/09
- Re: Setting variable with getopts, Dennis Williamson, 2021/08/09
- Re: Setting variable with getopts, Dennis Williamson, 2021/08/09
- Setting variable with getopts,
hancooper <=
- Setting variable with getopts, hancooper, 2021/08/09
- Re: Setting variable with getopts, Dennis Williamson, 2021/08/09
- Setting variable with getopts, hancooper, 2021/08/09