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

标签 linux bash shell getopts

当我像这样运行命令时:

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

相关文章:

Bash for 循环 - 在 n 之后命名(这是用户的输入)

linux - 无法从 shell 脚本终止进程

linux - 使用特定部分的 shell 从属性文件中获取值

linux - Docker Devmapper 空间问题 - 增加大小

linux - Centos 7 与 PHP 7.2 Pthreads 无法加载 redis.so

Bash IF 语句 : string comparison of command output always false

linux - 使用 bash shell 解析 CSV 以打印得分最高的行

mysql - 默认 MySQL 数据库名称

python - 即使在连接丢失或 SSH 连接终止后,如何让 python 脚本(abc.py)继续在 AWS 上执行?

Linux Shell 脚本 - 带通配符的字符串比较