bash - 在 Bash 中,为什么在函数中使用 getopts 只能使用一次?

标签 bash getopts

<分区>

我正在尝试在 macOS Sierra 上创建一个简单的函数来计算字符串中的字符数。这工作正常(添加到我的 bashrc 文件):

function cchar() {
    str=$1
    len=${#str}
    echo "string is $len char long"
}

$ cchar "foo"
string is 3 char long

我试图用 -a 选项扩展它,所以我将它添加到我的函数中(并将其余部分注释掉以供测试):

while getopts "a:" opt; do
    case $opt in
        a)
            echo "-a param: $OPTARG" >&2
            ;;
    esac
done

在编写本文时经过一些测试后,我注意到每次运行 cchar -a "test" 时,我都必须在没有选项 (cchar) 的情况下运行它,否则下次我使用 -a 选项运行它时,它无法识别该选项。

$ cchar

$ cchar -a "foo"
-a param: foo

$ cchar -a "foo"

$ cchar

$ cchar -a "foo"
-a param: foo

最佳答案

您必须重置变量 OPTIND,它跟踪当前位置参数编号。使该变量成为您的函数的本地变量就足够了。

关于bash - 在 Bash 中,为什么在函数中使用 getopts 只能使用一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42336595/

相关文章:

python - 使用 ssh 时 bash 中缺少 'read' 提示?

linux - 如何使用 curl 命令调用具有 getopts 的 bash 脚本?

c - C 中的 getopts,命令行参数

macos - 在 OSX Mavericks 中找不到 mvn 命令

bash - 如何将 wc -l 输出通过管道传输到 echo 输出

Bash getopts 命令

bash - 在 getopts 之后解析参数

linux - getopts 在 linux shell 脚本中抛出无效参数错误

linux - 在 bash 中确定批处理作业的 PID

Bash:如何使用运算符参数扩展${parameter@operator}?