2015-11-05 39 views
0

这可能是Bash loop control while if else with a return的副本。我正在查询的方法可能会有所不同。这是我的挑战。while if if bash

我想让我的bash脚本在文件中寻找一个字符串。如果找不到字符串,我希望它说出来,等待10秒钟,然后继续查找字符串。一旦找到字符串,我希望它退出并执行其他功能。我无法放置while和if的逻辑。代码如下:

while ! grep -q Hello "filename.txt"; do 
    echo "String Hello not found. Waiting 10 seconds and trying again" 
    sleep 10 
    if grep -q Hello "filename.txt"; then 
    echo "String Hello found in filename.txt. Moving on to next procedure" 
    sleep 2 
    return 0 
    fi 
    #do other functions here 
done 
exit 
+0

从表面上看,你删除了'if' ...' fi'和'从循环体中'执行其他函数'。你放弃了'如果'。 '做其他功能'的代码在循环之后。直到看到字符串,循环才会退出;当看到字符串时,其他函数将被执行。你可能会决定在循环中想要某种超时;计算迭代次数,如果字符串在一小时内没有出现(360次迭代),则放弃错误消息并退出。 –

回答

3

如何可以退出while循环的唯一方法是通过查找字符串。因此,不要检查循环内是否存在,并且即使在循环结束后也不检查它,它通过循环结束来保证:

while ! grep -q Hello filename.txt ; do 
    echo "String Hello not found. Waiting 10 seconds and trying again" 
    sleep 10 
done 
echo "String Hello found in filename.txt. Moving on to next procedure" 
+0

谢谢@choroba。这解决了它。 – ToofanHasArrived