2013-12-09 35 views
0

我想檢查從程序輸出的字符串,如果字符串匹配某個內容,while循環將停止程序。與此同時,我需要算多少次的程序運行:shell腳本:使用while循環來檢查字符串內容使用[]

x = "Lookup success" # this is supposed to be the output from the program 
INTERVAL=0 # count the number of runs 

while ["$x" != "Lookup failed"] # only break out the while loop when "Lookup failed" happened in the program 
do 
    echo "not failed"  # do something 
    $x = "Lookup failed"  # just for testing the break-out 
    INTERVAL=(($INTERVAL + 10)); # the interval increments by 10 
done 

echo $x 
echo $INTERVAL 

但這shell腳本不工作,與此錯誤:

./test.sh: line 9: x: command not found 
./test.sh: line 12: [[: command not found 

有人能幫助我嗎?我感謝您的幫助。

+0

如果它幫助你,請接受或提出答案。 – Anubhab

回答

1

[之後和]之前加一個空格。

另外,正如喬納森所說,你在任務中也不能有空間。

2

您需要在[命令名稱周圍有空格。在命令末尾的]參數之前還需要一個空格。

您也不能在shell中分配空間。並且您在循環中的分配在開始時不需要$

x="Lookup success" 
INTERVAL=0 # count the number of runs 

while [ "$x" != "Lookup failed" ] 
do 
    echo "not failed" 
    x="Lookup failed" 
    INTERVAL=(($INTERVAL + 10)) 
done 

echo $x 
echo $INTERVAL 
0

不知道是否有一個shell可以接受INTERVAL =((...));我在兩個平臺上的ksh和bash版本沒有。 INTERVAL = $((...))確實有效:

#!/bin/bash 

x="Lookup success" 
INTERVAL=0 # count the number of runs 

while [ "$x" != "Lookup failed" ] 
do 
    echo "not failed" 
    x="Lookup failed" 
    INTERVAL=$(($INTERVAL + 10)) 
done 

echo $x 
echo $INTERVAL 

Credits轉到@JonathanLeffler。我會很高興得票,這樣下次我不必複製粘貼其他人的解決方案來指出簡單的錯字(評論權利從rep> = 50開始)。