help-bash
[Top][All Lists]
Advanced

[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 15:46:53 +0000

Have introduced an echo so I can print the variable arg.

local shortopts="Vuhv:"
  while getopts $shortopts arg; do
    echo "arg: $arg"
    case $arg in

If I run the function the first time I get

myfunc -p 28
arg: p
val, arg: p  ;  OPTARG: 28
val: 28

But if I run the function again, I get

myfunc -p 12
val: 1

There seems to be some problem with the while loop.

‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Monday, August 9, 2021 2:48 PM, hancooper via <help-bash@gnu.org> wrote:

> I am experiencing difficulties setting a variable `p` that is supposed to be 
> set using getopts.
>
> status ()
> {
>
> local val=1
> local shortopts="Vuhp:"
>
> while getopts $shortopts arg; do
> case $arg in
>
> ........................................................
>
> =========================================================
>
> ("V")
> printf "%s\n" "V01 Jul 2021 Wk27"
> return
> ;;
> ("u")
> printf "%s\n" "-V, -u, -h"
> printf "%s\n" "getopt-status --"
> return
> ;;
> ("h")
> printf "%s\n" "Description."
> return
> ;;
> ("p")
> val="$OPTARG"
> printf '%s\n' "val, arg: $arg ; OPTARG: $OPTARG"
> ;;
> (:)
> echo "Current argument value, OPTARG: -$OPTARG" >&2
> echo "Must supply an argument to -$OPTARG" >&2
> ;;
> (?)
> printf "%s" "Invalid option, OPTARG: $OPTARG"
> ;;
> esac
> done
> shift "$OPTIND"
>
> echo "val: $val"
>
> }





reply via email to

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