Reputation: 85
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
Upvotes: 0
Views: 98
Reputation: 241748
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"
Upvotes: 4