I think you will have to use a temp file for this operation so that you can use the
&& operator to only run the mail command if the grep returned an exit status that says it had matches like this:
TMPFILE=`mktemp /tmp/mailqgrep.XXXXXX`; mailq | egrep 'rejected|refused' -A5 -B5 > "$TMPFILE" && mail -s 'dd' email@email < "$TMPFILE"; rm "$TMPFILE"
If you didn't mind the temp file sticking around somewhere and can use a static name for it, you could skip the special naming and deletion stuff:
mailq | egrep 'rejected|refused' -A5 -B5 > /tmp/mailqgrep && mail -s 'dd' email@email < /tmp/mailqgrep
Edit: After seeing glenn's answer I played with this some more and apparently assigning a variable using the
$() syntax returns the exit code of the command, so you can skip the test he used for the string length and use that instead. Here it is all in one command:
data=$(mailq | egrep 'rejected|refused' -A 5 -B 5) && mail -s 'dd' email@email <<< "$data"
Edit 2: After seeing Simon's answer I checked out my
mail program. It does not behave in the way he describes by default, but does have an option for that. From the man page:
-E If an outgoing message does not contain any text in its first or only message part, do not send it but discard it silently, effectively setting skipemptybody variable at program startup. This is useful for sending messages from scripts started by cron(8).
Making this possible:
mailq | egrep 'rejected|refused' -A 5 -B 5 | mail -E -s 'dd' email@email