Ksh: Send a mail in case grep finds something

I want to search a file if it contains special strings and if yes, the records found should be mailed.

I can either do it with a temporary file:

/usr/bin/grep somestring somefile > /tmp/tempfile && /usr/bin/mail -s "Found something" email@mycomp.com < /tmp/tempfile

... or by running the grep command twice:

/usr/bin/grep -q somestring somefile && /usr/bin/grep somestring somefile | /usr/bin/mail -s "Found something" email@mycomp.com

I wonder if there is another short and smart way doing this without using a file and without using grep twice and without do-loops?

This should run with AIX 6.1, preferably under ksh version 88.

try

grep somestring somefile | mailx -s "Found something" email@mycomp.com

Thanks, but unfortunately that sends an empty mail in case grep doesn't find anything.

then what you want to send in case grep dosent find anything??

No mail in that case.
Only in the rare case that something is found, the addresse should be notified.

try

if [ `grep somestring somefile | wc -l` -gt 0 ];
then
grep somestring somefile | mailx -s "Found something" email@mycomp.com
fi

That is what I already had. Please re-read my original post for what I am looking for.

your problem solved...
try

var=$(grep somestring somefile) && [[ ! -z "${var}" ]] &&  echo "${var}"|mailx -s "Found something" email@mycomp.com

Courtesy : Pilnet

1 Like

Thanks, but the result from grep may have multiple lines, that will be clutched together when stored in one variable.

If not too many matching lines, store them in a variable!

special=`grep somestring somefile`
if [ -n "$special" ]
then
  echo "$special" | mail ...
fi

---------- Post updated at 12:58 PM ---------- Previous update was at 12:35 PM ----------

Just seeing this is in principal the same as the previous answer.
No, the shell does not clutch anything together.
An echo $var does a reformatting, but not an echo "$var"

1 Like

Outch, sorry Makarand, I missed that small difference the double quotes make around the variable.
Thanks (from Germany), also to "Made in Germany" for pointing that out.

Makarand's solution can even be abbreviated, as grep gives returncode 0 if it was successful (and 1 if not):

var=$(grep somestring somefile) &&  echo "$var"|mailx -s "Found something" email@mycomp.com

Does anybody know where the limit is for the size of a variable (in ksh 88)?