Why does getopts only work for the first time?

Why does this option only work on first use and then ignored at another time? This is similar to reset when the option is not used.

Here is my function:

testopts() {
    local var="o false"
    while getopts "o" option; do
        case "${option}" in
            o)
                var="o true"
                ;;
        esac
    done
    echo $var
}

When launched, it returns true only when passing the option for the first time.

$ testopts
o false
$ testopts -o
o true
$ testopts -o
o false
+4
source share
1 answer

You need to add this line at the top of your function:

OPTIND=1

Otherwise, the sequential call of the function in the shell does not return it back, since the function is launched in the same shell every time.

According to help getopts:

, , getopts     shell variable $name, , ,      ,      OPTIND. OPTIND 1 ,      script.

+3

Source: https://habr.com/ru/post/1666755/


All Articles