[英]Array not passing values to for loop
我有下面的代碼,數組不將值傳遞給for循環。
echo "rops is ${rops[*]}"
for i in ${rops[*]}
do
if [[ ${rops[i]} == 4000 ]]; then
echo "issue there"
fi
done
+ echo 'rops is 931
32
32'
rops is 931
32
32
+ for i in '${rops[*]}'
+ [[ '' == 4000 ]]
+ for i in '${rops[*]}'
+ [[ '' == 4000 ]]
+ for i in '${rops[*]}'
+ [[ '' == 4000 ]]
-謝謝。
問題是i
包含數組中的值,而不是數組中的索引。
也就是說, i
第一次是931
,然后是32
,然后是31
,但是您沒有元素${rops[931]}
, ${rops[32]}
或${rops[31]}
,因此外殼給您一個空字符串,作為${rops[i]}
(無論如何應為${rops[$i]}
)。 因此,外殼執行其操作的原因有多種。
rops=(931 32 31)
echo "rops is ${rops[*]}"
for i in ${rops[*]}
do
echo "i = $i"
if [[ "${rops[$i]}" == 4000 ]]; then
echo "issue there"
fi
done
當使用bash
運行時,將產生:
rops is 931 32 31
i = 931
i = 32
i = 31
間距上的差異表明您沒有像此代碼那樣完全初始化數組。 您以某種方式獲得了與數組元素關聯的換行符。
for i in ${rops[*]}
使用for i in ${rops[*]}
表示法(或for i in "${rops[@]}"
使用for i in ${rops[*]}
表示法,這在多個級別上更好-嘗試使用值中帶有空格的數組元素以查看原因)給出數組中的元素。 如果您確實需要索引,則需要閱讀有關陣列的Bash手冊並使用:
rops=(931 32 31)
echo "rops is ${rops[*]}"
echo "indexes are ${!rops[*]}"
for i in "${!rops[@]}"
do
echo "i = $i; rops[$i] = ${rops[$i]}"
if [[ "${rops[$i]}" == 4000 ]]; then
echo "issue there"
fi
done
樣本輸出:
rops is 931 32 31
indexes are 0 1 2
i = 0; rops[0] = 931
i = 1; rops[1] = 32
i = 2; rops[2] = 31
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.