6

I've created a cron job that runs a shell script. I'd like the shell script to run and capture it's output and have it emailed upon completion. Here's what I have so far, but the mail message body is empty.

I've tried all of the following:

/root/myscript.sh | tee output.txt | mail -s "Email subject" me@mymail.com

/root/myscript.sh | tee output.txt | mail -s "Email subject" me@mymail.com &> /dev/null

/root/myscript.sh | tee output.txt && mail -s "Email subject" me@mymail.com < output.txt &> /dev/null

/root/myscript.sh > tee output.txt && mail -s "Email subject" me@mymail.com < output.txt &> /dev/null

All of these run properly, but they produce an email with an empty body. Running the script does produce output on stdout.

5
  • What is in "output.txt"? The first one should work fine. Does your script's output go to stdout or stderr? Jan 2, 2016 at 1:13
  • Does your version of cron not support emailing stdout automatically? It's a pretty standard thing...
    – Tyson
    Jan 2, 2016 at 1:14
  • 1
    Does output.txt have any contents after running your scripts? Maybe the terminal output you saw was on standard error: if so you need to redirect that as well, as in /root/myscript.sh 2>&1 | ....
    – AFH
    Jan 2, 2016 at 1:31
  • @AFH Please write this as an answer. Here's what worked for me /root/myscript.sh 2>&1 | tee output.txt | mail -s "Email subject" me@mymail.com.
    – Nilpo
    Jan 2, 2016 at 6:56
  • @AFH After further testing, the simpler /root/myscript.sh 2>&1 | mail -s "Email subject" me@mymail.com also works.
    – Nilpo
    Jan 2, 2016 at 6:59

1 Answer 1

10

The most likely reason for losing screen text on redirection is that the output was being sent to the standard error device. This will be confirmed if output.txt is empty after running the command.

To redirect standard error as well as standard output you need to add 2>&1 to your commands, as in:

/root/myscript.sh 2>&1 | tee output.txt | mail -s "Email subject" me@mymail.com

You should then see all your script's output in output.txt.

1
  • Thanks, that works. I was also able to do this without using tee.
    – Nilpo
    Jan 2, 2016 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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