0

This maybe a duplicate of Bash loop control while if else with a return. The method that I am inquiring about might be different. Here's my challenge.

I want my bash script to look for a string in a file. If the string is not found, I want it to say so, wait 10 seconds, and keep looking for the string. Once the string is found, I want it to exit and do other functions. I am having trouble placing the logic of while and if. Code below:

 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
1
  • Superficially, you remove the iffi and the do other functions here from the body of the loop. The if you discard. The 'do other functions' code goes after the loop. The loop won't exit until the string is seen; when the string is seen, the other functions will be executed. You may decide you want some sort of timeout on the loop; count the iterations and if the string hasn't appeared inside an hour (360 iterations), give up with an error message and exit. Commented Nov 5, 2015 at 16:51

1 Answer 1

4

The only way how the while loop can be exited is by finding the string. So, don't check for the presence again inside the loop, and don't check for it even after it, it's guaranteed by the fact the loop ended:

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @choroba. That fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.