2013-04-24 123 views
6

我想在bash中使用getopts處理命令行參數。其中一個要求是處理任意數量的選項參數(不使用引號)。使用getopts(bash)的多選項參數

1例(只抓住第一個參數)

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 
+2

這可能會幫助:http://stackoverflow.com/a/7530327/1983854 – fedorqui 2013-04-24 08:34:12

+0

詳細信息是必要的。當給定'getoptz.sh -s a -b c'時,你想要什麼行爲? '-b'是'-s'的參數,還是'-'表示一個新選項? – 2013-04-24 11:26:43

+0

相關,但決不是重複,[調用不同的選項和不同的參數爲每個選項](http://stackoverflow.com/questions/15442950/)。一般來說,最好使用標準的命令接口指南[POSIX Utility Conventions](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html) – 2013-04-24 13:17:14

回答

3

您可以自己分析命令行參數,但不能將getopts命令配置爲將多個參數識別爲單個選項。 fedorqui's recommendation是一個很好的選擇。

這是自己解析選項的一種方式:

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

的確,「識別單個選項的多個參數」是不可能的,但是可以重複該選項。我給答案增加了一個例子,因爲我認爲這是真正想要的。 – mivk 2013-12-24 13:42:07

11

我想你想的是從一個選項得到值的列表。爲此,您可以根據需要多次重複該選項,並將其參數添加到數組中。

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

輸出將是:

$ /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