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") }'
2
  • Someone else asked this exact question about 6 months ago on stackoverflow. Search the archives there.
    – Ed Morton
    Aug 16, 2019 at 9:14
  • Related
    – Thor
    Aug 20, 2019 at 16:53

1 Answer 1

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.

1
  • This worked great. Thanks! Aug 16, 2019 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.