Prevent email from being sent if nawk returns null

112 views Asked by At

I was able to get my script to successfully email me at regular intervals with the help of another user here. My next question, is that I'd like for it to ONLY email me if the output is not null.

I have a nawk set up to email me the output, and the script is set up to run every 5 minutes via crontab. Due to the number of log files, this would mean that I'd receive 9 emails every 5 minutes which would blow up my inbox.

Current script:

nawk '$0~s{for(c=NR-b;c<=NR+a;c++)r[c]=1}{q[NR]=$0}END{for(c=1;c<=NR;c++)if(r[c])print q[c]}' b=4 a=4 s="Bind value for HASCHILDREN = 0" filename | mail -s "Output from crontask" myemail

Current crontab:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /home/me/crontask
2

There are 2 answers

1
glenn jackman On

In order to test the output of the nawk command, you need to save it somewhere. I'd recommend you use a variable:

output=$(
    nawk '
        $0 ~ s {for (c=NR-b; c<=NR+a; c++) r[c]=1}
        {q[NR] = $0}
        END {for (c=1; c<=NR; c++) if (r[c]) print q[c]}
    ' b=4 a=4 s="Bind value for HASCHILDREN = 0" filename
)
[[ "$output" ]] && mail -s "Output from crontask" [email protected] <<< "$output"

I assume your shell is bash.

0
demonic240 On

Using Shelter's advice. I was able to output the results to a temporary file, then ran his if/then statement to email myself if it wasn't null. I've confirmed that it's now working.