February 3rd, 2017, 12:21 PM
-
Email Error Notifications on Cron Bash Script mv cp rsync
Wondering if anyone can point me to an example of how to setup a bash script that executes cp mv and rsync commands and only sends an email if there were errors with any of those commands and what the errors are. In addition it should email if the cron event to execute the script fails, or in other words if the bash script doesn't run at all or exits prematurely with an error.
Thank you!
February 12th, 2017, 07:57 AM
-
Check the value of $? (store it in a variable for later reference) after each 'critical' command:
Code:
num_errors=0
mv this to.that
mv_cc=$?
if [ $mv_cc != 0 ]
then
num_errors+=1
echo do something here
fi
cp over.there to.here
cp_cc=$?
if [$cp_cc != 0]
then
num_errors+=1
do something about copy fail
fi
command -x -y -x >$$.out.txt 2>$$.err.txt
cmd_cc=$?
if [ $cmd_cc != 0]
then
num_errors+=1
parse $$.out.txt to determine more info about fail
fi
.
.
. more stuff ...
.
if [ $num_errors > 0 ]
then
echo Arrange a mail saying all that has gone wrong
fi
Not sure about Linux but most Unix systems drop the owning user a mail in the event of a cron job failing, so no need to do much there
The moon on the one hand, the dawn on the other:
The moon is my sister, the dawn is my brother.
The moon on my left and the dawn on my right.
My brother, good morning: my sister, good night.
-- Hilaire Belloc
February 20th, 2017, 05:28 AM
-
Yes, cron will email the owner of the account under which the crontab is running.
You may also use the MAILTO environment variable to send any output generated by your script to a specific email address, e.g.:
MAILTO=your_email@domain.com
0 10 * * * /path/to/bash_script