How can I run another command if there is any input on the standard input

commonly used in situations like this:

some command with no normal output | ifinput mail -s 'some output' me

link|improve this question

feedback

3 Answers

up vote 2 down vote accepted

The simplest solution would be using a file (if you dare!). The -s switch means "file is not zero size". The &> redirections includes errors as well (means that stdout and stderr will be sent).

OUTFILE=/tmp/command.out
some command &> $OUTFILE
[ -s "$OUTFILE" ] && mail -s "subject here" email@example.com < "$OUTFILE"

Edit: the comment below by glenn jackman contains even a better solution.

link|improve this answer
2  
Don't really need a file for that: output=$(some command); [[ -n "$output" ]] && mail ... <<< "$output" – glenn jackman Jul 15 '11 at 17:33
feedback

A little trickery with read:

$ echo 1 | { read -t 0 -N 0 && cat ; } 
1
$ { read -t 0 -N 0 && cat ; } 
$ 
link|improve this answer
Hmm looks promising - can you show an example sending "1" to the mail command? In your example, would I just replace cat with the command that I wanted to run? – ckliborn Jul 15 '11 at 15:11
That's correct. – Ignacio Vazquez-Abrams Jul 15 '11 at 15:13
feedback

You could also create a shell script. That script could first call some command that redirects the output to a file and then call the mail command from within the script to send it out which is essentially what SamKrieg is doing without the need to create a shell script. A reason for the script may depend on if you want to run this command as a cron job or somehting.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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