- 論壇徽章:
- 0
|
本帖最后由 dickgz1z 于 2010-06-22 12:05 編輯
- #!/bin/sh
- for i in 1 2 3 4 5; do
- a=0
- b=10
- c=20
- while [ $i -gt 3 ]
- do
- a=`expr $a + 1`
- b=`expr $b - 1`
- c=`expr $c + 1`
- done
- echo "the value of a :${a}\nthe value of b :$\nthe value of c :${c}"
- done
復制代碼 bash下經(jīng)過while循環(huán)的變量值在循環(huán)結(jié)束后會丟失,這里我通過上面這個比較簡單的例子說下,輸出結(jié)果是:- the value of a :0
- the value of b :10
- the value of c :20
- the value of a :0
- the value of b :10
- the value of c :20
- the value of a :0
- the value of b :10
- the value of c :20
復制代碼 變量a,b,c的值并未改變。請問大家有遇到這樣的問題嗎?是怎樣解決的?
P.S.:
QUOTE:試試這個應該對了
值初始化的位置有問題。按原while的寫法,可以這樣寫,但是看上去怪怪的:
zenith518 發(fā)表于 2010-06-22 08:15
其實不是值初始化的位置有問題,而是有時必須在每一次for循環(huán)里初始化變量值,例如把一個目錄的所有文件放入for循環(huán),以變量作為計數(shù)器計算每個文件的行數(shù)。至于把while換成if的做法雖然在此例可行,但換了其他情況if還是不能做讀文件操作:- for FILE in test/*.txt; do
- line_count=0
- while read line
- do
- line_count=`expr $line_count + 1`
- done<$FILE
- echo "$FILE has $line_count lines."
- done
復制代碼 像上面這段代碼,line_count是可以獲得test目錄下每個文件的行數(shù)的,但如果換成cat $FILE|while read line ,line_count的值每一次都將是0。上例就是必須在每一次for循環(huán)開始時初始化變量的情況,幸虧用輸入重定向的辦法可以解決問題。 |
|