为什么此选项仅在首次使用时起作用,而后每隔一次被忽略?就像不使用该选项时将其重置。
这是我的功能:
testopts() {
local var="o false"
while getopts "o" option; do
case "${option}" in
o)
var="o true"
;;
esac
done
echo $var
}
运行它时,仅在首次传递该选项时才返回true。
$ testopts o false $ testopts -o o true $ testopts -o o false
您需要在函数顶部添加以下行:
OPTIND=1
否则,由于每次都在同一个shell中运行函数,因此在shell中连续调用该函数不会将其重置。
按help getopts
:
每次调用它时,
getopts
都会将下一个选项放在shell变量中$name
,如果不存在则初始化名称,并将下一个要处理的参数的索引放入shell变量中OPTIND
。每次调用shell或shell脚本时都会被OPTIND
初始化1
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句