【问题标题】:While loop with if bash使用 if bash 循环
【发布时间】:2016-02-06 14:56:51
【问题描述】:

这可能与Bash loop control while if else with a return 重复。我询问的方法可能不同。这是我的挑战。

我希望我的 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

【问题讨论】:

  • 从表面上看,您从循环体中删除了iffido other functions hereif 你丢弃。 “做其他功能”代码在循环之后。在看到字符串之前,循环不会退出;当看到字符串时,将执行其他函数。您可能决定要在循环中设置某种超时;计算迭代次数,如果字符串在一小时内没有出现(360 次迭代),则放弃错误消息并退出。

标签: bash if-statement while-loop


【解决方案1】:

退出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"

【讨论】:

  • 谢谢@choroba。这解决了它。
猜你喜欢
  • 2017-03-06
  • 2013-12-20
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多