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

╄→гoц情女王★ 提交于 2019-11-28 03:23:50
tail -fn0 logfile | \
while read line ; do
        echo "$line" | grep "pattern"
        if [ $? = 0 ]
        then
                ... do something ...
        fi
done

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.

Ari Maniatis

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.

Batter and simple:

tail -f log.txt | egrep -m 1 "error"
echo "Found error, do sth."
...

Simple Automated Solution that covers a lot of scenarios:

USAGE:

logrobot localhost [default-dir],fixer,[exit-codes],[command/script-to-run-per-exit-code] [feature] [logfile] [age] [str-1] [str-2] [WARN] [CRIT] [tag] [option]

EXAMPLE:

logrobot  localhost  /tmp/logXray,fixer,0y-1y-2y,0-uname,1-who,2-uptime  autonda  /var/log/kern.log  60m  'error'  '.'  1  2  app_err_monitor  -ndshow

With this tool, you can monitor specific patterns in a log file and then trigger a command or script when the patterns are found...or NOT Found!

The scripts or commands can be set to run based on thresholds and exit codes.

Tool can be downloaded directly here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!