I am making a script for my school, and I was wondering how I could check a file, and if the string isn't in the file, do a code, but if it is, continue, like this:
while [ -z $(cat File.txt | grep "string" ) ] #Checking if file doesn't contain string
do
echo "No matching string!, trying again" #If it doesn't, run this code
done
echo "String matched!" #If it does, run this code
You can do something like:
$ if grep "string" file;then echo "found";else echo "not found"
To do a loop :
$ while ! grep "no" file;do echo "not found";sleep 2;done
$ echo "found"
But be carefull not to enter an infinite loop. string or file must be changed otherwise the loop has no meaning.
Above if/while works based on the return status of the command and not on the result. if grep finds string in file will return 0 = success = true if grep does not find string will return 1 = not success = false
By using ! we revert the "false" to "true" to keep the loop running since while loops on something as soon as it is true.
A more conventional while loop would be similar to your code but without the useless use of cat and the extra pipe:
$ while [ -z $(grep "no" a.txt) ];do echo "not found";sleep 2;done
$ echo "found"
A simple if statement to test if a 'string' is not in file.txt
:
#!/bin/bash
if ! grep -q string file.txt; then
echo "string not found in file!"
else
echo "string found in file!"
fi
The -q
option (--quiet
, --silent
) ensures output is not written to standard output.
A simple while loop to test is a 'string' is not in file.txt
:
#!/bin/bash
while ! grep -q string file.txt; do
echo "string not found in file!"
done
echo "string found in file!"
Note: be aware of the possibility that the while loop may cause a infinite loop!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With