问题
I have a script that I run nightly in cron to backup some postgres databases for several hosts on my network. I have a way of getting alerted that the script fails by leveraging the exit status, but it doesn't tell me WHY it failed.
Based off the following code, how can I capture any errors that occur when the script is run, and email them to me so I can have a better understanding of what happened.
FILEDATE=`date '+%Y-%m-%d'`
BASEDIR=/u1/$1/db_dumps
PGDUMP=/path/to/pg_dump
HOST=$1
DB=$2
if [ $DB == all ]
then 
    for ALLDUMPS in db1 db2 db3
        do
        ssh root@$HOST "env PGUSER=pguser PGPASSWORD=pgpassword $PGDUMP -Fc $ALLDUMPS" | pbzip2 > $BASEDIR/$FILEDATE-$HOST-$ALLDUMPS.dump.bz2
            if [ $? -ne 0 ]
                then mutt -s "dbdumper could not create a backup of $ALLDUMP from $HOST" me@myemail.com < /dev/null
            fi
        done
else 
    ssh root@$HOST "env PGUSER=pguser PGPASSWORD=pgpassword $PGDUMP -Fc $DB" | pbzip2 > $BASEDIR/$FILEDATE-$HOST-$DB.dump.bz2
if [ $? -ne 0 ]
    then mutt -s "dbdumper failed to create a backup of $DB from $HOST" me@myemail.com < /dev/null
fi
fi
    回答1:
Capture stderr from the ssh command, and email that to yourself.
stderr=$( ssh root@$HOST "env PGUSER=user PGPASSWORD=pw $PGDUMP -Fc $ALLDUMPS" | 
          pbzip2 2>&1 > "$BASEDIR/$FILEDATE-$HOST-$ALLDUMPS.dump.bz2" )
if [ $? -ne 0 ]; then
   subj="dbdumper could not create a backup of $ALLDUMP from $HOST"
   mutt -s "$subj" me@myemail.com <<< "$stderr"
fi
    来源:https://stackoverflow.com/questions/6784295/capturing-and-mailing-bash-script-errors