在 bash 中使用 getopts 的多個選項參數

在 bash 中使用 getopts 的多個選項參數

我正在嘗試使用處理命令列參數getopts在 bash 中使用處理命令列參數。要求之一是處理任意數量的選項參數(不使用引號)。

第一個範例(僅取得第一個參數)

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

第二個例子(我希望它的行為像這樣,但不需要引用參數”

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

有沒有辦法做到這一點?

這是我現在的程式碼:

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

請注意,我想以這種方式支援多個標誌,例如

madcap:~/projects$ ./getoptz.sh -s a b c -u 1 2 3 4
-s was triggered
Argument: a b c
-u was triggered
Argument: 1 2 3 4

答案1

我認為最好的方法是對每個參數使用 -s ,即-s foo -s bar -s baz如果您仍然想支援單一選項的多個參數,我建議您不是使用getopts

請看一下下面的腳本:

#!/bin/bash

declare -a sargs=()

read_s_args()
{
    while (($#)) && [[ $1 != -* ]]; do sargs+=("$1"); shift; done
}

while (($#)); do
    case "$1" in
        -s) read_s_args "${@:2}"
    esac
    shift
done

printf '<%s>' "${sargs[@]}"

-s偵測到時,read_s_args將使用命令列上的其餘選項和參數來呼叫。read_s_args讀取其參數,直到到達下一個選項。 -s 的有效參數儲存在sargs陣列中。

這裡有一個樣本輸出:

[rany$] ./script -s foo bar baz -u a b c -s foo1 -j e f g
<foo> <bar> <baz> <foo1>
[rany$]

相關內容