使用 getopts (bash) 的多个选项参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16186392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:16:10  来源:igfitidea点击:

Multiple option arguments using getopts (bash)

linuxbashshellunixgetopts

提问by user1117603

I am trying to process command line arguments using getopts in bash. One of the requirements is for the processing of an arbitrary number of option arguments (without the use of quotes).

我正在尝试在 bash 中使用 getopts 处理命令行参数。要求之一是处理任意数量的选项参数(不使用引号)。

1st example (only grabs the 1st argument)

第一个示例(仅获取第一个参数)

madcap:~/projects$ ./getoptz.sh -s a b c
-s was triggered
Argument: a

2nd example (I want it to behave like this but without needing to quote the argument"

第二个例子(我希望它表现得像这样,但不需要引用参数”

madcap:~/projects$ ./getoptz.sh -s "a b c"
-s was triggered
Argument: a b c

Is there a way to do this?

有没有办法做到这一点?

Here's the code I have now:

这是我现在拥有的代码:

#!/bin/bash
while getopts ":s:" opt; do
    case $opt in
    s) echo "-s was triggered" >&2
       args="$OPTARG"
       echo "Argument: $args"
       ;;
   \?) echo "Invalid option: -$OPTARG" >&2
       ;;
    :) echo "Option -$OPTARG requires an argument." >&2
       exit 1
       ;;
    esac
done

回答by mivk

I think what you want is to get a list of values from a single option. For that, you can repeat the option as many times as needed, and add it's argument to an array.

我认为您想要的是从单个选项中获取值列表。为此,您可以根据需要多次重复该选项,并将其参数添加到数组中。

#!/bin/bash

while getopts "m:" opt; do
    case $opt in
        m) multi+=("$OPTARG");;
        #...
    esac
done
shift $((OPTIND -1))

echo "The first value of the array 'multi' is '$multi'"
echo "The whole list of values is '${multi[@]}'"

echo "Or:"

for val in "${multi[@]}"; do
    echo " - $val"
done

The output would be:

输出将是:

$ /tmp/t
The first value of the array 'multi' is ''
The whole list of values is ''
Or:

$ /tmp/t -m "one arg with spaces"
The first value of the array 'multi' is 'one arg with spaces'
The whole list of values is 'one arg with spaces'
Or:
 - one arg with spaces

$ /tmp/t -m one -m "second argument" -m three
The first value of the array 'multi' is 'one'
The whole list of values is 'one second argument three'
Or:
 - one
 - second argument
 - three

回答by chepner

You can parse the command-line arguments yourself, but the getoptscommand cannot be configured to recognize multiple arguments to a single option. fedorqui's recommendationis a good alternative.

您可以自己解析命令行参数,但getopts无法将该命令配置为识别单个选项的多个参数。fedorqui 的推荐是一个不错的选择。

Here is one way of parsing the option yourself:

这是自己解析选项的一种方法:

while [[ "$*" ]]; do
    if [[  = "-s" ]]; then
        # -s takes three arguments
        args="  "
        echo "-s got $args"
        shift 4
    fi
done