当我像这样运行命令时:
$: ./script -r f1 f2
:
它检测“-r”标志并将递归标志设置为 1。
$: ./script directory/-r
:
getopts
根本没有检测到 -r
标志。因此,在 case 语句中,它永远不会检测到 -r
标志,因此 while 循环甚至根本不会运行。如何解决这个问题?
RECURSIVE_FLAG=0
while getopts ":rR" opt ; do
echo " opt = $opt"
set -x
case "$opt" in
r) RECURSIVE_FLAG=1 ;;
R) RECURSIVE_FLAG=1 ;;
:)echo "not working" ;;
*)echo "Testing *" ;;
esac
done
最佳答案
它与斜杠无关。 getopts
在到达第一个不以 -
开头的参数时停止处理选项。这是 documented行为:
When the end of options is encountered,
getopts
exits with a return value greater than zero.OPTIND
is set to the index of the first non-option argument, and name is set to?
.
你声称它在你使用时有效
./script f1 f2 -r
是完全错误的。我在脚本末尾添加了 echo $RECURSIVE_FLAG
,当我以这种方式运行它时,它回显了 0
。
如果你想允许更自由的语法,在文件名后加上选项(比如 GNU rm
),你需要自己做一些参数解析。将您的 getopts
循环放在另一个循环中。当 getopts
循环结束时,您可以:
# Find next option argument
while [[ $OPTIND <= $# && ${!OPTIND} != -* ]]; do
((OPTIND++))
done
# Stop when we've run out of arguments
if [[ $OPTIND > $# ]]; then
break
fi
关于linux - 选项前有参数时 getopts 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53200469/