2012-12-02 38 views
4

我有兩個我想要循環的數組。我正確地構造這些數組,並且在進入for循環之前,我會迴應它們以確保數組中的一切都正常。 但是當我運行該腳本,它輸出一個錯誤:語法錯誤:使用Bash時預期的操作數

l<=: syntax error: operand expected (error token is "<=" 

我諮詢了強大的谷歌,我的理解是因爲缺乏第二個變量的遭遇,但我前面提到的我做呼應的價值觀和一切似乎沒問題。下面是摘錄..

#!/bin/bash 
    k=0 
    #this loop is just for being sure array is loaded 
    while [[ $k -le ${#hitEnd[@]} ]] 
     do 
     echo "hitEnd is: ${hitEnd[k]} and hitStart is: ${hitStart[k]}" 
     # here outputs the values correct 
     k=$((k+1)) 
    done 
    k=0 
    for ((l=${hitStart[k]};l<=${hitEnd[k]};l++)) ; do //this is error line.. 
     let array[l]++  
     k=$((k+1)) 
done 

的變量在for循環正確迴應,但for循環將不會工作。我在哪裏錯了?

作爲gniourf_gniourf回答:

"... At some point, k will reach the value ${#hitEnd[@]}, and this is exactly when hitEnd[k] is not defined and expands to an empty string! Bang!"

意味着誤差輸出是在循環開始時不顯示,但是,當k具有比陣列的指數爲更大的值,指向一個索引陣列不包括...

回答

4

這是因爲在某些時候${hitEnd[k]}展開爲空(它是未定義的)。我收到與((l<=))相同的錯誤。你應該寫你的for環路:

k=0 
for ((l=${hitStart[0]};k<${#hitEnd[@]} && l<=${hitEnd[k]};l++)); do 

,以便總是對應於定義的字段數組${hitEnd[@]}在索引k

此外,而不是

k=$((k+1)) 

,你可以只寫

((++k)) 

完成!

你的腳本中使用更好的現代慶典的做法修訂:

#!/bin/bash 
k=0 
#this loop is just for being sure array is loaded 
while ((k<=${#hitEnd[@]})); do 
    echo "hitEnd is: ${hitEnd[k]} and hitStart is: ${hitStart[k]}" 
    # here outputs the values correct 
    ((++k)) 
done 
k=0 
for ((l=hitStart[0];k<${#hitEnd[@]} && l<=hitEnd[k];++l)); do 
    ((++array[l])) 
    ((++k)) 
done 

現在,我也不太清楚了for循環不正是你想要它......難道你的意思是這樣呢?

#!/bin/bash 
# define arrays hitStart[@] and hitEnd[@]... 
# define array array[@] 

#this loop is just for being sure array is loaded 
for ((k=0;k<${#hitEnd[@]};++k)); do 
    echo "hitEnd is: ${hitEnd[k]} and hitStart is: ${hitStart[k]}" 
    # here outputs the values correct 
    ((++k)) 
done 

for ((k=0;k<${#hitEnd[@]};++k)); do 
    for ((l=hitStart[k];l<=hitEnd[k];++l)); do 
     ((++array[l])) 
    done 
done 
+0

感謝gniourf_gniourf,會盡量在後一點.. – teutara

+0

我還是不明白清楚爲什麼我在問題中提到的情況不起作用,但是謝謝你的努力.. – teutara

+0

我以爲你會理解它!注意變量'k'總是如何遞增的,並且記住'for'循環中的測試部分(即'l <= hitEnd [k]'部分)在每次通過時被評估! –

1

有點繃帶-Y,但你重寫你的for循環變成一個while循環:

l="${hitStart[k]}" 
while [[ "$l" -le "${hitEnd[k]}" ]]; do 
     let array[l]++  
     k=$((k+1)) 
     l=$((l+1)) 
done 
+0

謝謝你sampson-chen ..你激勵了我,它的工作原理.. – teutara

相關問題