多次使用 getopts 和 case

问题描述 投票:0回答:1

我正在将一个单独的文件放入我的 .bashrc 中。该文件包含与此类似的函数:

function some_function() {
    if [[ "$#" -eq 0 ]]; then
        return 1
    else
        while getopts "s:td:" opt; do
            case $opt in
                s) echo 's';;
                t) echo 't';;
                d) echo 'd';;
                *) echo 'default';;
            esac
        done
    fi
}

当我在命令行运行时

some_function -s 123
,我得到了预期的结果。
当我第二次运行完全相同的命令时,它不会进入 while 循环,而是进入函数。
你能解释一下为什么吗?谢谢

bash scripting getopts
1个回答
0
投票

如果您要多次拨打

OPTIND
,则需要将
1
重置为
getopts

getopts

每次调用时,

getopts
都会将下一个选项放入shell变量名称中,如果不存在则初始化name,并将下一个要处理的参数的索引放入变量
OPTIND
中。每次调用 shell 或 shell 脚本时,
OPTIND
都会初始化为
1
。 当选项需要参数时,
getopts
将该参数放入变量
OPTARG
中。 ** 外壳不会自动重置
OPTIND
;如果要使用一组新参数,则必须在同一 shell 调用中多次调用
getopts
之间手动重置它。

function some_function() {
    if [[ "$#" -eq 0 ]]; then
        return 1
    else
        OPTIND=1
        while getopts "s:td:" opt; do
            case $opt in
                s) echo 's';;
                t) echo 't';;
                d) echo 'd';;
                *) echo 'default';;
            esac
        done
    fi
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.