2013-10-16 31 views
-1

我正在寫一個bash腳本這將輸入參數的名稱使用一個變量的值,該命令是這樣的:在爭吵

command -a -b -c file -d -e 

我想檢測一個特定的參數( -b)與它的特定的位置($ 1,$ 2,$ 3)

#! /bin/bash 
counter=0 
while [ counter -lt $# ] 
do 
    if [ $($counter) == "-b" ] 
    then 
     found=$counter 
    fi 
    let counter+=1 
done 

問題上升$($counter)。有沒有辦法使用$counter來調用參數的值?例如,如果counter=2,我想調用參數$2的值。 $($counter)不起作用。

+2

使用'getopts'。例如http://stackoverflow.com/a/14203146/1983854可以幫助。 – fedorqui

+0

好的謝謝!我會研究它,但如果我想要以下文件名,例如-b文件名,「getopts」是否也提供此功能? –

+0

是的。你看過[documentation](http://linux.die.net/man/1/getopt)嗎? –

回答

2

你可以在沒有getopts的情況下完成這個任務(但仍然推薦),通過重做你的循環。

counter=1 
for i in "[email protected]"; do 
    if [[ $i == -b ]]; then 
     break 
    fi 
    ((counter+=1)) 
done 

只是直接迭代參數,而不是迭代參數位置。


bash也不會允許間接參數擴展,使用的語法如下:本

#! /bin/bash 
counter=0 
while [ counter -lt $# ] 
do 
    if [ ${!counter} = "-b" ] # ${!x} uses the value of x as the parameter name 
    then 
     found=$counter 
    fi 
    let counter+=1 
done 
+1

不要在單括號表示法中使用'==','bash'接受它,但它不符合POSIX標準,而其他的shell會扼殺它。其餘的+1! –

+0

無論如何,非POSIX shell可能會扼住「$ {!counter}」)但是你一般都是正確的。 – chepner

+0

你有一個點;-) –