Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
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).

some command &> $OUTFILE
[ -s "$OUTFILE" ] && mail -s "subject here" < "$OUTFILE"

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

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

A little trickery with read:

$ echo 1 | { read -t 0 -N 0 && cat ; } 
$ { read -t 0 -N 0 && cat ; } 
share|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

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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