Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faulty tail syntax or grep command?

Tags:

bash

I've been given the following code:

tail -fn0 /var/log/messages | \  
while read line ; do  
       echo "$line" | grep "test"  
       if [ $? = 0 ]  
       echo "Running information gathering"  
       then  
etc...etc  

What it's supposed to do is continually monitor the added lines of the "/var/tmp/messages" file and if one contains the word "test" then execute the rest of the script and exit when done.
It's executing the rest of the script as soon as any line is added to the messages file, irrespective of line content. I've added echo commands, and $line contains the new log file line correctly. I've tried changing the test "$? = 0" to "$? = 1" but it makes no difference.
Could someone please give me a pointer?

Thanks @TomFenech

like image 332
Andy Kendall Avatar asked Nov 04 '14 14:11

Andy Kendall


1 Answers

I would suggest that instead of using a loop, you can make things a lot simpler by just using grep:

tail -fn0 /var/log/messages | grep -q test
echo "Running information gathering"
# rest of script

grep -q exits after the first match, so your script will continue as soon as the first match is found.

like image 59
Tom Fenech Avatar answered Sep 28 '22 08:09

Tom Fenech