首页 > 解决方案 > 如何在 bash 中访问命令行标志的多个选项

问题描述

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

./program.sh -a -b # #
./program.sh -b # # -a
./program.sh -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

输出应该是两个方向上从 # 到 # 的字母,但我已经开始工作了,我唯一的问题实际上是接收输入。

标签: bashinputcommand-lineargumentsgetopts

解决方案


也许这个循环会起作用,而不是:

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,而不是根据需要获取下一个位置参数。


推荐阅读