redirect only the standard error output to mail

I'm writing a script using file descriptor 2 (std error) to send an email only if the command fails or errors out but the script always emails me irrepective of whether it fails or not. It will not email the /tmp/check.error file output if doesn't error out just the mail with the subject "Cannot run check script on machB".

Any suggestions would be really appreciated. Thanks

###(Note: I have a mail problem with the one on 4th line, the other one works OK)
==========================================================================================
#!/bin/ksh

echo "" >> /tmp/sync.error

rsync -goptvz -e ssh /var/sync.all machB:/var/sync.all 2>>/tmp/sync.error

ssh -l root machB '/usr/local/check' 2>>/tmp/check.error | mail -s "Cannot run check script on machB" email@removed  

if [ $? = 0 ]
then
  date +"%D %T:$script Successfully executed." >> /dev/null 

else
  date +"%D %T:$script Unsuccessfully executed." >> /tmp/sync.error
  date +"%D %T: Exiting script." >> /tmp/sync.error
  mail -s "Cannot sync the sync.all file to machB, plz. look at /tmp/sync.error" email@removed < /tmp/sync.error

  exit 1
fi

date +"%D %T: Sync of printcap.all file completed." >> /tmp/sync.error

A generic way to handle any errors the script would be to get rid of your return code logic and
put this at the top of your script. Remove the piped mail statement also.

trap 'mail -s "Error on line $LINENO; rc=$?" email@address </tmp/sync.error >/dev/null' ERR

or if you only care about the return from the ssh line... change

ssh -l root machB '/usr/local/check' 2>>/tmp/check.error | mail -s "Cannot run check script on machB" email@removed 

to

ssh -l root machB '/usr/local/check' 2>>/tmp/check.error || mail -s "Cannot run check script on machB" email@removed </tmp/check.error >/dev/null

and remove your if test

Thanks, I have used the trap command and it works good for me, also I brought down the code to a few lines, just wondering how the return code rc=$? values can be evaulated.

Trying to setup rsync backup in the same fashion, but having much more limited knowledge than you gentlemen about shell scripts, can either of you give me an example of the 'finished' script you are talking about that is fully functional?

I am setting up a server that will use the rsync command and ssh to backup from local directories to an account at rsync.net and need to have emails sent to me if it fails.

Thanks.