Reputation: 151
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
Upvotes: 6
Views: 13017
Reputation: 74625
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.
Upvotes: 7
Reputation: 785196
In BASH you can use glob matches and avoid grep
:
tail -fn0 /var/log/messages |
while read -r line; do
if [[ "$line" == *test* ]]; then
echo "Running information gathering"
fi
done
PS: You could use grep -q
instead to get correct exit status based on the successful match being found.
Upvotes: 2