Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

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

I have a simple script on my home server to sync data to my backup drive to be stored.

Right now it runs multiple rsyncs one after another.

Sometimes rsync fails on one or two of them. When this happens, I want it to email me saying it failed, I already have it email me a report, but, I want a way to know if it fails.

If Rsync exits with a non 0 code it means failure. So I would need a simple bit of code to check the rsync status and if it's not 0, allow me to execute an action.

Does anyone have any tips on how i would accomplish this? Thank you.

share|improve this question

Basically you want to make use of the variable $?. This variable contains the return status of the last run command.

% /bin/false
% echo $?
% /bin/true
% echo $?

You can use these constructs to run rsync and send you mail if it succeeds (echo true) or send you mail if it fails (echo false).

% /bin/false && echo true || echo false
% /bin/true && echo true || echo false

Something like this:

% rsync \
    && (echo "succeed" | mail -s "succeed" <email>) \
    || (echo "failure" | mail -s "failure" <email>)
share|improve this answer
Thank you. Exactly what was needed. Utilized the propose variable, however, ran a short if statement after each cycle as there are multiple rsyncs actions and I needed individual status. – Marcos Sander Feb 3 '13 at 22:30
Glad it helped. Yeah was showing you the technique, expand it as needed. Please upvote and access this answer if it's the most appropriate one! – slm Feb 3 '13 at 22:37

for using in script I prefer this universal construction:

check_exit_code() {
    if [ "$exit_code" -ne "0" ] ; then
        echo "$1"
        echo "exit with exitcode $exit_code"
        return 1

 check_exit_code "smth failed"

You can add using sendmail at this function or add MAILTO in your crontab

share|improve this answer
The function could start with "$@" and end with return "$exit_code" Then the function call could be put in front of the command to check instead of as a separate line. – kasperd Nov 13 '14 at 12:49

A suggestion/ optimization, to preceeding anwers:

If it is crucial, i'd make the script confirm an OK instead of a fail, for example with a

wget ""

and let the webserver deal with checking if there was no call home. (first DB entry with the wget call, then cron check if there was an entry for that machine) and react in any/many ways (mail, sms/text, ...)

because there are so many reasons why a mail never reaches its target. It's a lot more work, I agree...

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.