1

I found this line:

sh script.sh | grep 'NO' 2>&1 > grep.log && /usr/bin/mail -s "grep found something" m@mail.com < grep.log

which will write the output of script.sh to grep.log and then email that to an email m@mail.com

Is there anyway to remove the part where this wrote to grep.log and simply mail the output of the script without having to write it to a file?

Kohjah Breese
  • 171
  • 1
  • 11
  • 2
    Yes, but only if you would accept empty mails when grep doesn't find anything – Michael Hampton Dec 17 '18 at 18:35
  • @MichaelHampton According to `man grep` on my comp grep returns `0` (OK) only when a line is selected. – AnFi Dec 17 '18 at 19:45
  • 1
    Aha, I see someone has demonstrated my point; see Romeo Ninov's answer. That is the way to do it, but you will always get a mail, even when nothing is found. – Michael Hampton Dec 17 '18 at 19:47

2 Answers2

3

You could capture output to a shell variable instead of a log file:

found_stuff=$(sh script.sh | grep 'NO' 2>&1) &&
    echo "$found_stuff" | /usr/bin/mail -s "grep found something" m@mail.com

(Note: the first line must be a plain variable assignment, not export var= or local var= or declare var= or anything like that. In those cases the && depends on the exit status of the export etc command, not the grep.)

Gordon Davisson
  • 11,036
  • 3
  • 27
  • 33
2

To send directly mails you can use command like this:

sh script.sh | grep 'NO' 2>&1 | /usr/bin/mail -s "grep found something" m@mail.com
Romeo Ninov
  • 3,195
  • 2
  • 13
  • 16