为什么getopts仅在第一次使用? [英] Why does getopts only work the first time?

查看:116
本文介绍了为什么getopts仅在第一次使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此选项仅在首次使用时起作用,而后每隔一次被忽略?就像不使用该选项时将其重置.

Why does this option only work the first time it's used, then ignored every other time? It's like it's being reset when the option is not used.

这是我的职能:

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

运行它时,仅在首次传递该选项时才返回true.

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

$ testopts
o false
$ testopts -o
o true
$ testopts -o
o false

推荐答案

您需要在函数顶部添加以下行:

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

OPTIND=1

否则,由于每次都在同一个shell中运行该函数,因此在shell中连续调用该函数不会将其重置为空.

Otherwise successive invocation of the function in shell are not resetting this back since function is being run in the same shell every time.

根据help getopts:

每次调用它时,getopts都会将下一个选项放在 shell变量$name,如果不存在,则初始化名称,以及 下一个要处理到shell中的参数的索引 变量OPTIND.每次shell或 OPTIND都初始化为1. 一个shell脚本被调用.

Each time it is invoked, getopts will place the next option in the shell variable $name, initializing name if it does not exist, and the index of the next argument to be processed into the shell variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is invoked.

这篇关于为什么getopts仅在第一次使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆