2010-07-01 37 views
1

我想將許多參數傳遞給一個shell腳本,我不知道它們將會有多少個參數,我想處理它們。我做了下面的代碼:在shell腳本中循環參數數組,不知道有多少個參數?

int=$1 
src=$2 

r=$3 
string=$4 

duration=$5 

./start.sh $int $r $src "$string" 
sleep $duration 

shift; shift; shift; shift; shift 

while [ $# -gt 2 ] 
do 
    r=$1 
    string=$2 
    duration=$3 
    ./change.sh $int $r "$string" 
    sleep $duration 
    shift; shift; shift 
done 

這一工程,但只有一個時間,現在我想這個腳本來運行所有的時間,我的意思是使用while 1但由於參數列表是空的,不會以這種方式工作在代碼的末尾!

有沒有辦法做這樣的事情在shell腳本下面的「僞代碼」:

for(i=0 ; i<arguments.count; i++){ 
    //do something with arguments[i] 
} 

或複製參數數組到另一個數組,這樣我可以在以後使用它,我想要的方式。 我的意思是我可以將$*[email protected]arg複製到另一個陣列中嗎?

任何幫助,高度讚賞。

回答

3

參數的數量存儲在參數#中,可以通過$#訪問。

一個簡單的循環遍歷所有的參數可以寫成如下:

for arg 
do 
    # do something with the argument "arg" 
done 
+0

我可以使用'$ arg [i]'之類的東西嗎? – Reem 2010-07-01 09:14:47

+0

是的,''$ {arg [$ i]}「'(注意引號和大括號)。 – Philipp 2010-07-01 09:18:30

+0

'i = 1; echo「$ {arg [$ i]}」' 什麼都沒有打印:( – Reem 2010-07-01 09:32:22

0

您可以使用$#來獲取傳遞給腳本的參數數量,或者使用[email protected]來獲取整個參數列表。

0
declare -a array_list 
index=0 
for arg 
do 
    array_list[$index]=$arg 
    echo ${array_list[$index]} #just to make sure it is copied :) 
    ((index++)) 
done 

現在,我使用array_list做我想做的事情有參數列表。 謝謝