如何在bash中访问命令行标志的多个选项

问题描述 投票:0回答:1

我想访问多个命令行输入标志,但我无法让它工作。输入顺序不受我的控制,格式为(#是数字,而不是注释)

./program.sh -a -b # #
./program.sh -b # # -a
./program.sh -b # #
  • -a没有选项,它只是一个开关的开关
  • -b总是跟着两个数字。

我尝试使用getopts,这适用于-a和第一个-b,但我无法访问第二个数字。有时-a-b之后出现,将输入的“余数”视为字符串不能按预期工作。我尝试使用一个循环,当它找到-b时,查看下面两个要设置的值,如下所示:

for i in "$@"; do 
    case "$i" in
        -a)
            upperCase=true;
            ;;
        -b)
            first=$(($i+1));
            second=$(($i+2));
            ;;
        *)
            ;;

    esac
done

输出应该是两个方向打印的#到#的字母,但是我的工作正常,我唯一的问题是实际接收输入。

bash input command-line arguments getopts
1个回答
1
投票

也许这个循环可行,相反:

while [[ $# -gt 0 ]]
do
    case "$1" in
        -a)
            upperCase=true;
            ;;
        -b)
            first=$2;  # Take the next two arguments
            second=$3; 
            shift 2    # And shift twice to account for them
            ;;
        *)
            ;;

    esac
    shift  # Shift each argument out after processing them
done

$(($i+1))只是在变量i中添加一个,而不是根据需要获取下一个位置参数。

© www.soinside.com 2019 - 2024. All rights reserved.