2

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
demonic240
  • 55
  • 1
  • 5
  • 1
    There may be some "advanced" syntax you can apply, but the simple solution is to redirect nawk output into tmp file, then use `if [[ -s tmpFile ]] ; then mailx -S ... user1@mycomp.com,usr2@xyz.com < tmpFile ; rm tmpFile; fi` Good luck! – shellter Sep 10 '13 at 16:53
  • So I'd add "> /home/me/crontmp" to the end of the nawk script instead of sending an email. And then on a second line, add "if [[ -s /home/me/crontmp ]] ; then mail -S "Output Test" myemail@mail.com < /home/me/crontmp ; rm /home/me/crontmp; fi" ? – demonic240 Sep 10 '13 at 17:09
  • that's what I'd try although Glenn Jackman's solution is (as usual) excellent too. Good luck! – shellter Sep 10 '13 at 17:35
  • as you're using `nawk`, that implies to me that you're using Solaris. @Glennjackman s solution will not work with normal the std `#!/bin/ksh` at the top. try `#!/usr/xpg4/bin/ksh` or srch for `dtksh`. Basically, ksh in Solaris is ksh88, you'll have to find where ksh93 is hiding. (I don't have access to a Solaris machine anymore). Good luck. – shellter Sep 12 '13 at 09:12

2 Answers2

1

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" me@example.com <<< "$output"

I assume your shell is bash.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

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.

demonic240
  • 55
  • 1
  • 5