How to email the output of a cronjob to different addresses

By jbayer - Last updated: Thursday, May 10, 2012 - Save & Share - Leave a Comment

Cron is a wonderful tool on a Linux/Unix box.  Normally, when a job runs and some output is generated, it is emailed to the owner of the job.  You can alter this by added the following line to the crontab file:

MAILTO=address@domain.com

However, if you have a number of jobs which are run by a single user, and you want the output from each job to go to a different address, this mechanism falls down.

The following is a simple way to control where the output is emailed to.  All you have to do is source the redirect file, then call the startredirect function specifying the email address(s), subject and if desired, error subject with whatever you want.

The script redirects stdout and stderr to a file, runs the code, and then emails the file to the specified address at the end.  The file is removed by the trap code when the script exits.

#!/bin/bash
. /usr/local/bin/redirect
startredirect "jonathan.bayer@achieve3000.com" "Test subject" "error test subject"
echo "test"
echo "test error" >&2
endredirect

Put the following into:  /usr/local/bin/redirect, the only permissions it needs is read:

#
# startredirect
#
# parameters:
#
# Email address
# Email subject
# Error email subject (optional)
#
function startredirect {
 if [ "$1" = "" -o "$2" = "" ]; then
 echo "No email and/or subject specified, not redirecting output"
 return
 fi
 MAILTO=$1
 SUBJECT=$2
 ERRSUBJECT=$3
fout=/tmp/$$fout$$.txt
 fouterr=$fout
[ "$ERRSUBJECT" != "" ] && fout=/tmp/$$fouterr$$.txt
################
 # Set a trap here for normal exit signals.
 # It says that no matter what signal you exit with, be it normal (0), or some
 # of the abnormal ones, remove the output files in /tmp.
 # If it's a really abnormal one, like an invalid memory ref that causes a
 # SIGSEGV (11) it will not clean up, because presumably you would want to
 # check it out. But 1 2 3 and 15 are all generated intentionally by users.
 ################
 trap endredirect 0 1 2 3 15
# Capture current stout and stderr
 exec 3>&1
 exec 4>&2
# Redirect stdout and stderr to output file
 exec 1>$fout
 [ "$fout" = "$fouterr" ] && exec 2>>$fout
 [ "$fout" != "$fouterr" ] && exec 2>$fouterr
}
#
# endredirect
#
# No parameters
#
function endredirect {
 # Restore stdout and stderr
 exec 1>&3
 exec 2>&4
# Send the mail, a second one if fouterr is different than fout
 [ -s $fout ] && cat $fout | mail $MAILTO -s "$SUBJECT"
 [ "$fout" != "$fouterr" -a -s $fouterr ] && cat $fouterr | mail $MAILTO -s "$ERRSUBJECT"
 rm -f $fout $fouterr >/dev/null 2>&1
}
Posted in Administration, Bash, Programming • • Top Of Page
1,020 views

Write a comment

asd