Search code examples
bashgreptail

Monitor tail of log file for string, if you don't find it, quit


Thousands of people on the web use tail to monitor a log file for a string, and if they don't find it, keep monitoring. It's the opposite of the problem I have -- I am trying to radically conserve resources, and I don't want a constant thread monitoring the log: I'm trying to set up a cron job to run it every half hour. But that means the Bash script, both tail and grep, have to monitor for the string and then quit, whether it finds it or no. Here's my best attempt:

LOG_FILE="/var/log/syslog"
SEARCHED="fallback errored"

( tail -f -n0 "$LOG_FILE" & ) | while IFS= read -r line; do
    if [ $(echo "${line}" | grep -q "${SEARCHED}") ] ; then
        curl -X POST https://maker.ifttt.com/trigger/EthFail/with/key/XXXXX
        touch "MonitorRanAndIamProofWhen"
    fi
done
exit 0

But it just keeps running... Tried putting tail in its own subprocess and adding a -t time flag to the read statement. Still sits there watching.


Solution

  • If you want to find the string ${SEARCHED}, you don't need the test command [ ].

    ( tail -f -n0 "$LOG_FILE" & ) | while IFS= read -r line; do
        if $(echo "${line}" | grep -q "${SEARCHED}") ; then
    

    Well, does the following command mean that the sub process is ended if the following file is created?

            touch "MonitorRanAndIamProofWhen"