I'm trying to modify a script which emails a user group the contents of a directory. The modification I'm looking for is to check the script below to see if it has valid output before sending.

The script is:

cd $foo/bar && ls | mail -s "Filenames in the \$foo/bar Directory" john.smith@who.com

I want to test if the file is null before sending this email, as this will go on three dozen servers and many to the same person/people, so I don't want to send a bunch of blank emails (which is the status quo).

I have looked at other similar questions, but none of them quite scratch the itch. This one is closest:


but is for a file attached, which won't work. Also, man mail returns a -E flag that is supposed to perform the content check, but I've played with it and my version doesn't seem to support the -E option (which is not something that can readily be changed). I get an error mail: invalid option -- E.

Any help would be appreciated. It doesn't have to be a one liner, but that sure would help!

EDIT - I need the directories to be dismissed in the output check, if this is possible! I did not clarify this originally, but if $foo/bar has a directory of /errors can this be avoided?

marked as duplicate by Gilles shell Jul 11 '16 at 23:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


You could trying testing with wc -l, something like:

cd $foo/bar && [ `ls | wc -l` -gt 0 ] && ls | mail
  • 1
    And, of course, you should always use the actual full paths of all commands in your actual script. – MAP Jul 11 '16 at 23:06
  • The problem with using the full path is that on each server it's slightly different, but the shortcut is identical on all of them. Thanks! – SomeGuy Jul 13 '16 at 14:25

I've done this before with a setup similar to:

out=`cd $foo/bar && ls` ; [[ -n "$out" ]] && echo "$out" | mail -s "Filenames in the \$foo/bar Directory" john.smith@who.com

Not the answer you're looking for? Browse other questions tagged or ask your own question.