Home > Back-end >  How To Send email alert on log file entry with awk in Linux?
How To Send email alert on log file entry with awk in Linux?

Time:06-14

I'm working on a script to monitor a log of jobs executed and I want to receive a mail notification with the line where appears the job in the body of the mail. This is what I got so far but it keeps throwing error, I can make it work but just with an empty body. Could you please help?

Job="jobname"

tail -fn0 logfile.log | awk -v Jobs="$Job"'/jobname/ 
{ 
    system("grep -i "Jobs" logfile.log | mail -s "Jobs Is Completed" [email protected]") 
    exit
}'

CodePudding user response:

What's wrong with just:

Job="jobname"
tail -fn0 logfile.log |
grep --line-buffered -i "jobname.*$Job" |
mail -s "$Job Is Completed" [email protected]"

Your use of jobname as literal in 2 places and a shell variable named Job with an awk variable named Jobs populated from it and both containing jobname anyway was very confusing so hopefully you can tweak the above to do whatever you need to do if the variable usage above is not quite right.

CodePudding user response:

watchdog.sh

#!/bin/bash
mailWorker(){  
    while read -r line; do
        if [[ $line == *$match* ]]
        then
            # mailing
            grep -i "Jobs" "$logfile" | mail -s "Jobs Is Completed" [email protected] 
            break
        fi
    done
}

logfile="/path/to/logfile.log"
match="jobname" 

if [ ! -f "$logfile" ]; then
  touch "$logfile"
fi

tail -f --lines=0 "$logfile" | mailWorker
  • Related