Shell function to tail a log file for a specific string for a specific time Shell function to tail a log file for a specific string for a specific time linux linux

Shell function to tail a log file for a specific string for a specific time


#!/bin/bashtail -f logfile | grep 'certain_word' | read -t 1200 dummy_var[ $? -eq 0 ]  && echo 'ok'  || echo 'server not up'

This reads anything written to logfile, searches for certain_word, echos ok if all is good, otherwise after waiting 1200 seconds (20 minutes) it complains.


You can do it like this:

start_time=$(date +"%s")while truedo    elapsed_time=$(($(date +"%s") - $start_time))    if [[ "$elapsed_time" -gt 1200 ]]; then        break    fi    sleep 1    if [[ $(grep -c "specific string" /path/to/log/file.log) -ge 1 ]]; then        break    fidone


You can use signal handlers from shell scripts (see http://www.ibm.com/developerworks/aix/library/au-usingtraps/index.html).

Basically, you'd define a function to be called on, say, signal 17, then put a sub-script in the background that will send that signal at some later time:

timeout(pid) {   sleep 1200   kill -SIGUSR1 $pid}watch_for_input() {   tail -f file | grep item}trap 'echo "Not found"; exit' SIGUSR1timeout($$) &watch_for_input

Then if you reach 1200 seconds, your function is called and you can choose what to do (like signal your tail/grep combo that is watching for your pattern in order to kill it)