Keep looking for file and search for a string

Hi,
I need to a program tht will keep looking for that particular file and search for a string, if found kick of a process else exit with condition 1. Pls advice if this can be done by tail cmd or while looop.

What OS are you on?

I use Linux

Suppose if you are looking inside file "/mylocation/myfile.log" for a particular string "Match Found", write a shell script as shown below and run it in background.

#!/bin/bash

my_file="/mylocation/myfile.log"
my_string="Match Found"

tail -F "$my_file" | while read line ; do
if test -n "$(echo "$line" | grep "$my_string")" ; then
echo "Match found!"
exit 0
else
exit 1
fi
done

meharo

Something like

#!/bin/bash
if grep $string $file
then
    Kick
else
    exit 1
fi
exit 0

Sorry but i don't really understand what you mean by "kick of a process" or is it "kick off" ? If so the use kill or killall (depending on if you have the process ID or name)

To kick off means to start...

I would suggest:

grep -q "$string" "$file"

Otherwise the output of grep will be visible on stdout. Also: use quotes as with out the the code will break if there are spaces or special characters in the strings.

This is confusing as you say you want the program to loop but also to exit if it does not find the matching string. You cannot loop and exit the script so what is it you are trying to do?

Hi meharo,

Thanks for your reply. How can we modify the code if we need to search for multiple files.

 
#!/bin/bash
 
my_file1="/mylocation/myfile1.log"
my_file2="/mylocation/myfile2.log"
my_string="Match Found"
 
tail -F "$my_file1" "$my_file2" | while read line ; do
if test -n "$(echo "$line" | grep "$my_string")" ; then
echo "Match found!"
exit 0
else
exit 1
fi
done

The above program will wait for both file1 and file2. Whenever it finds a file with proper string match, condition triggers.

The else condition to quit the program (exit 1) has to be used wisely. If you are looking for some 'lock' files with specific string content, the program can wait for the file(s) to occur in specific path and act immediately. If the file is a log file and always present in path, it is not wise to use the else logic, it will just quit the program after reading the first line itself.

meharo

to recursively search a string in files in a dir try

find . -name <name / pattern of your file> -print | xargs grep <string to be searched> 2>/dev/null

Cheers