Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While file doesn't contain string BASH

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
like image 419
Jacob Collins Avatar asked Feb 21 '17 20:02

Jacob Collins


2 Answers

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"
like image 65
George Vasiliou Avatar answered Oct 30 '22 09:10

George Vasiliou


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!

like image 3
Roald Nefs Avatar answered Oct 30 '22 09:10

Roald Nefs