Shellscript to monitor a log file if keyword triggers then execute a command?
Asked Answered
M

4

51

Is there a cheap way to monitor a log file like tail -f log.txt, then if something like [error] appears, execute a command?

Thank you.

Mannerless answered 2/12, 2010 at 3:10 Comment(0)
B
70
tail -fn0 logfile | \
while read line ; do
        echo "$line" | grep "pattern"
        if [ $? = 0 ]
        then
                ... do something ...
        fi
done
Buehler answered 2/12, 2010 at 3:16 Comment(4)
oh, one more thing, the tail -fn0 logfile seems to be expire since the HTTP server log file are quickly renamed and gzip'ed. The script is still monitor the old file-descriptor I think? Is there a way to auto update file inode or something after a period of time for the tail command?Mannerless
Just add a --retry to the tail command, or use -F instead of -f. That should do it.Photoperiod
Also consider grep -q to set the return code without displaying the matching lines.Bawdyhouse
the issue with this is, that logs like catalina,out (apache) have history, so "finished in" kinda patterns already exist. is there a way only check for future logs ?Grazia
D
16

I also found that you can use awk to monitor for pattern and perform some action when pattern is found:

tail -fn0 logfile | awk '/pattern/ { print | "command" }'

This will execute command when pattern is found in the log. Command can be any unix command including shell scripts or anything else.

Duvetyn answered 19/4, 2013 at 19:51 Comment(1)
I would change -f to -F.Dilute
P
5

An even more robust approach is monit. This tool can monitor very many things, but one of them is that it will easily tail one or more logs, match against regex and then trigger a script. This is particularly useful if you have a collection of log files to watch or more than one event to trigger.

Prolusion answered 14/7, 2013 at 12:0 Comment(0)
B
2

Better and simple:

tail -f log.txt | egrep -m 1 "error"
echo "Found error, do sth."
...
Bergamo answered 26/7, 2017 at 8:4 Comment(1)
Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.Rockwell

© 2022 - 2024 — McMap. All rights reserved.