1

I need to write a script that will tail a log and look for a specific message. When the message appears, the script needs to continue to monitor the log, and when the message has not appeared again for 5 seconds, I need the script to execute a command.

Here's the pseudo code:

tailing log file Found message "an error occurred" The message repeats anywhere from 10 to 20 times. Once the message has stopped scrolling, wait 5 seconds and execute "systemctl restart myservice"

I was trying to use awk, but I'm having trouble figuring out how to wait until the message stops scrolling before I execute the command. Here's the code I had:

tail -F /var/log/mylog.log | awk '
                    /TestString goes here/ { system("sleep 5; systemctl restart myservice") }'

1 Answers1

0

You could do it with bash, corutils timeout and an intermediary file:

restart-server.bash

# Wait for the initial "TestString"
tail -n0 -F logfile |
while IFS= read -r; do 
  if [[ "$REPLY" == TestString ]]; then 
    break
  fi
done

# See if "TestString" repeats at least every 5 seconds
touch ts
while [ -e ts ]; do
  rm -f ts
  timeout 5 bash -c '
tail -n0 -f logfile |
while IFS= read -r; do 
  if [[ "$REPLY" == TestString ]]; then 
    touch ts
  fi
done
'
done

systemctl restart myserver

See Greg's wiki for more on bash while-read loops.

Thor
  • 17,182