【发布时间】: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
【问题讨论】:
-
从表面上看,您从循环体中删除了
if…fi和do other functions here。if你丢弃。 “做其他功能”代码在循环之后。在看到字符串之前,循环不会退出;当看到字符串时,将执行其他函数。您可能决定要在循环中设置某种超时;计算迭代次数,如果字符串在一小时内没有出现(360 次迭代),则放弃错误消息并退出。
标签: bash if-statement while-loop