选项前有参数时 getopts 不起作用

getopts doesn't work when there are arguments before options

当我 运行 这样的命令时:

$: ./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