是bash getopts功能对命令行选项有破坏性吗?

时间:2008-09-28 00:12:18

标签: bash shell

你能在同一个脚本中使用bash“getopts”两次吗?

我有一组选项,根据特定选项的价值,这意味着不同的东西。由于我无法保证getopts会首先评估该特定选项,因此我想使用该特定选项运行一次getopts,然后使用其他选项再次运行它。

2 个答案:

答案 0 :(得分:4)

是的,之后只需重置OPTIND。

#!/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

答案 1 :(得分:2)

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

有关详细信息,请参阅bash手册页。

HTH。

欢呼声,

罗布

相关问题