2013-03-16 55 views
0

我正在嘗試在cygwinbash腳本中使用getopts。以下是代碼:在cygwin上使用getopts的錯誤

#!/bin/bash 

# Sample program to deal with getopts. 

echo "Number of input arguments = $#"; 
i=0; 

while [ ${i} -lt 10 ]; 
do 
    i=$[${i}+1]; 
    echo ${i}; 
done 

while getopts ":a:b:c:e:" opt; 
do 
    case ${opt} in 
    a) 
    echo "-a was triggered with argument: ${OPTARG}"; 
    ;; 

    b) 
    echo "-b was triggered with argument: ${OPTARG}" 
    ;; 

    c) 
    echo "-c was triggered with argument: $[OPTARG}" 
    ;; 

    e) 
    echo "-e was triggered with argument: ${OPTARG}" 
    ;; 

    ?) 
    echo "Invalid argument: ${OPTARG}" 
    ;; 
    esac 
done 

當我運行上面的代碼,我得到以下錯誤:

./getOpts_sample.bash: line 37: syntax error near unexpected token `done' 
./getOpts_sample.bash: line 37: `done' 

我無法理解這個錯誤背後的原因。爲什麼getopts循環在第一個循環中不起作用?是否因爲我的系統沒有安裝getopts?我該如何檢查?

回答

2

這不是特定於cygwin;有語法錯誤行26:

echo "-c was triggered with argument: $[OPTARG}" 

取代[{,它會工作。

第11行註釋:echo ${i}錯誤,請使用echo ${!i}打印第i個參數。

注意第10行:語法$[ ]現在已過時;你可以使用(()),而不是像這樣:

((i++)) 

,甚至更好,通過替換8-12行:

for ((i=0; i<10; i++)); do echo ${!i}; done 
+0

這是一個偉大的答案,我希望我可以給它一個以上的給予好評! – ruakh 2013-03-16 18:04:15

+0

謝謝!我想我需要一些睡眠..我看不到正確的代碼。 – Sriram 2013-03-16 18:14:33