2017-02-21 57 views
0

我正在測試一個簡單的程序shell(sh)。Shell sh,語法while(condition)

我正在使用while循環,但它顯示一個錯誤。

./essai.sh:5號線:測試:參數太多

這是代碼:

#!/bin/sh 

numero=1 
max=3 
while test [ $numero -le $max ] 
do 
ping -c 2 127.0.0.1 
numero=$(($numero + 1)) 
printf $numero 
sleep 5 
done 

回答

1

條件的說法是錯誤 變化情況從

while test [ $numero -le $max ] 

while [ $numero -le $max ] 
+1

它對空間非常敏感......我之前測試過這個解決方案,但我沒注意空間。 無論如何,謝謝你,它現在的作品! –

+0

或者直接刪除方括號:'while while test $ numero -le $ max' – cfromme

+1

或者使用括號將比較看起來更自然:'while((numero <= max))'.... OOPS,剛纔注意到:我們在這裏有Posix Shell,而不是bash。在這種情況下,這種替代方法不起作用。 – user1934428

1

測試關鍵字已被刪除:

while [ $numero -le $max ] 

你也知道

for numero in $(seq 1 3) ; do echo $numero ; done 
3

「[]」 的意思是 「試驗」,所以,你可以該行更改爲

while test $numero -le $max 

while [ $numero -le $max ] 

順便說一句:「[]」和條件表達式之間的空格是必要的。