2012-07-12 43 views
0

我可以將for循環中的參數列表視爲列表嗎?我可以通過列表索引訪問列表中的元素嗎? 使此僞代碼運行:在Bash中:我可以將for循環中的參數列表視爲列表嗎?

#!/bin/bash 
for i in 1 2; do 
    j=the next element in the for loop 
    echo current is $i and next is $j 
done 

輸出應該是對於第一次迭代:

電流爲1和下一個是2

會是用於第二次迭代什麼循環?

回答

1

沒有(實用)的方式來窺探什麼,在未來的元素將會有一個for循環。您必須將值存儲在別處和/或使用不同類型的循環。

您可以使用位置參數或數組。

位置參數保證不稀疏。

set -- {a..f} 
n=1 

while ((n<=$#)); do 
    printf 'cur: %s%.s%s\n' "${!n}" $((++n)) ${!n:+", next: ${!n}"} 
done 

bash數組很稀疏。如果您不是直接使用for循環來迭代值,則應該使用索引。

arr=({a..f}) idx=("${!arr[@]}") 

while ((n<${#idx[@]})); do 
    printf 'cur: %s%s\n' "${arr[idx[n]]}" ${idx[++n]:+", next: ${arr[idx[n]]}"} 
done 

即使你認爲你可以保證連續的元素,這種方法並不是一個壞主意。

輸出爲兩個例子:

cur: a, next: b 
cur: b, next: c 
cur: c, next: d 
cur: d, next: e 
cur: e, next: f 
cur: f 
3

我覺得bash的人總是在最複雜的事情。你能不能也住:

# Let's say we want to access elements 1,3,3,7 in this order 
cur=$1 
for next in "$3" "$3" "$7" 
do 
    printf "cur: %s, next: %s\n" "$cur" "$next" 
    cur=$next 
done 

What will it be for the second last iteration of the loop?

如果你不能回答這個問題,我也沒有。這通常意味着你覺得太複雜了。我認爲更簡單的我的上述版本並沒有以一種非常自然的方式擁有這個角落,因爲它的不同之處在於最後一次迭代「缺失」。