49

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.

Anonymous Penguin
  • 2,027
  • 4
  • 34
  • 49
est
  • 11,429
  • 14
  • 70
  • 118

4 Answers4

70
tail -fn0 logfile | \
while read line ; do
        echo "$line" | grep "pattern"
        if [ $? = 0 ]
        then
                ... do something ...
        fi
done
Wesley Rice
  • 2,711
  • 19
  • 8
  • 2
    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? – est Dec 10 '10 at 03:35
  • 11
    Just add a --retry to the tail command, or use -F instead of -f. That should do it. – Zizzencs Dec 14 '10 at 14:32
  • 3
    Also consider `grep -q` to set the return code without displaying the matching lines. – Adam Liss Jul 14 '13 at 12:03
  • 1
    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 ? – Siddharth May 30 '17 at 14:18
15

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.

xwin
  • 355
  • 3
  • 3
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.

Paul M Furley
  • 1,005
  • 1
  • 8
  • 12
Ari Maniatis
  • 8,038
  • 3
  • 19
  • 28
2

Better and simple:

tail -f log.txt | egrep -m 1 "error"
echo "Found error, do sth."
...
Santosh Joshi
  • 3,290
  • 5
  • 36
  • 49
Changbin Du
  • 501
  • 5
  • 11
  • 2
    Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) 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. – Toby Speight Jul 26 '17 at 09:26