bash getopts函数是否破坏了命令行选项?

bash getopts函数是否破坏了命令行选项?,bash,shell,Bash,Shell,可以在同一个脚本中使用bash“getopts”函数两次吗 我有一组选项,根据特定选项的值,它们意味着不同的事情。因为我不能保证getopts会首先计算该特定选项,所以我想只使用该特定选项运行getopts一次,然后使用其他选项再次运行它。是的,只需重置optin,然后再重置 #!/bin/bash set -- -1 while getopts 1 opt; do case "${opt}" in 1) echo "Worked!";; *) exit

可以在同一个脚本中使用bash“getopts”函数两次吗


我有一组选项,根据特定选项的值,它们意味着不同的事情。因为我不能保证getopts会首先计算该特定选项,所以我想只使用该特定选项运行getopts一次,然后使用其他选项再次运行它。

是的,只需重置optin,然后再重置

#!/bin/bash

set -- -1
while getopts 1 opt; do
    case "${opt}" in
        1) echo "Worked!";;
        *) exit 1;
    esac
done

OPTIND=1
set -- -2
while getopts 2 opt; do
    case "${opt}" in
        2) echo "Worked!";;
        *) exit 1;
    esac
done

getopts不修改原始参数,这与较早的getopt独立可执行文件不同。您可以反复使用bash内置的getopts,而无需修改原始输入

有关更多信息,请参见bash手册页

干杯


Rob

不幸的是,这主要证明了
set--…
是破坏性的。为了显示getopts是非破坏性的,您需要再次使用第二次查找选项1(并省略第二次
set--
语句)。或者,在每个循环后回显“$@”。