在Bash中,为什么在函数中使用getopts只工作一次? [英] In Bash, why does using getopts in a function only work once?
问题描述
我正在尝试在macOS Sierra上创建一个简单的函数来计算字符串中的字符.可以正常工作(添加到我的bashrc
文件中):
I'm trying to create a simple function on macOS Sierra that counts the characters in a string. This works fine (added to my bashrc
file):
function cchar() {
str=$1
len=${#str}
echo "string is $len char long"
}
$ cchar "foo"
string is 3 char long
我正在尝试使用-a
选项对其进行扩展,因此我将其添加到了我的函数中(并注释掉了其余部分以进行测试):
I'm trying to expand it with a -a
option, so I added this to my function (and commented the rest out for testing):
while getopts "a:" opt; do
case $opt in
a)
echo "-a param: $OPTARG" >&2
;;
esac
done
在编写此代码进行一些测试之后,我注意到每次我运行cchar -a "test"
时,都必须在没有选项(cchar
)的情况下运行它,否则,下一次我使用-a
选项运行它时,它不会无法识别该选项.
After some testing while writing this, I've noticed everytime I run cchar -a "test"
, I have to run it without options (cchar
) otherwise the next time I run it with the -a
option, it doesn't recognise the option.
$ cchar
$ cchar -a "foo"
-a param: foo
$ cchar -a "foo"
$ cchar
$ cchar -a "foo"
-a param: foo
推荐答案
您必须重置变量OPTIND
,该变量会跟踪当前的位置参数编号.使该变量在您的函数中本地化就足够了.
You have to reset the variable OPTIND
, which keeps track of the current positional argument number. It should suffice to make that variable local to your function.
这篇关于在Bash中,为什么在函数中使用getopts只工作一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!