LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash script to continuously read log file (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-to-continuously-read-log-file-4175475039/)

socalheel 08-28-2013 10:42 AM

bash script to continuously read log file
 
i need to develop a bash script to continually read a log file and if a certain string exists, then notify via email.

what i have so far is below, can someone help guide me on this?

Code:

#!/bin/bash

string=fail

while true
do
if tail -f /path/to/file | grep $string
then
echo -e "String found on $HOSTNAME" | mail -s "Subject" dummy@iam.com
fi
done


linosaurusroot 08-28-2013 10:55 AM

Your problem here is "tail -f" won't finish and the things you want won't happen.

Do this in Perl using select() to test when there is new data to read.

druuna 08-28-2013 11:17 AM

Have a look at this:
Code:

#!/bin/bash

string=fail

tail -n0 -F /pat/to/file | \
while read LINE
do
  if echo "$LINE" | grep "$string" 1>/dev/null 2>&1
  then
    echo "String found on $HOSTNAME" | mail -s "Subject" dummy@iam.com
  fi
done

The bold part suppresses any output to screen (stdout and stderr), edit if you want to see either/both on screen.

jpollard 08-28-2013 12:42 PM

Another option is to put an entry in the syslog.conf file to invoke the script when entries appear. The advantage this has is that it will allow you to exclude some messages (such as boot, kernel messages, mail...) and only handle the class of message you need. (The section on named pipes).

You can also check the section on "Shell execute", which allows the program executed to receive the message as a single parameter. The advantage this one has is that the selected messages will be the only thing passed, and it simplifies the handling (no tail -f problems due to buffering) - Each message is sent independently of the others. The script devolves into the fragment:

Code:

if echo "$1" | grep "$string" 1>/dev/null 2>&1
  then
    echo "String found on $HOSTNAME" | mail -s "Subject" dummy@iam.com
fi


socalheel 08-28-2013 01:19 PM

thanks druuna and jpollard for your input. i've got the solution and verified it to work.

Code:

#!/bin/bash

string="fail"

tail -n 0 -F /path/to/file | \
while read LINE
do
echo "$LINE" | grep -q $string
if [ $? = 0 ]
then
echo -e "$string found on $HOSTNAME" | mail -s "Something's wrong on $(hostname)" whomever@wherever.com
fi
done

the one problem i had with that script was when i run it, it continued to stay in a loop and would never give me a [root@hostname]# prompt. i got around that by a nohup startup
Code:

nohup ./script.name.sh 0<&- &>/dev/null &


All times are GMT -5. The time now is 02:15 PM.