How to mail output of shell script as a cron job
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" [email protected]
You should then see all your script's output in output.txt
.
Related videos on Youtube
Nilpo
I am a freelance technology writer and developer specializing in mobile and web technologies. I also have an extensive background in networking and systems administration.
Updated on September 18, 2022Comments
-
Nilpo over 1 year
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" [email protected] /root/myscript.sh | tee output.txt | mail -s "Email subject" [email protected] &> /dev/null /root/myscript.sh | tee output.txt && mail -s "Email subject" [email protected] < output.txt &> /dev/null /root/myscript.sh > tee output.txt && mail -s "Email subject" [email protected] < 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.
-
Nilpo over 8 yearsThanks, that works. I was also able to do this without using
tee
.