Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I've a script which will take backup of mysql db through mysqldump. I'd like add another option in this script to send an automatic email if the dump is successful or failure.

Here's the script:

#!/bin/sh
BACKUP=/data/backup/sql2/new_backup/daily
cd $BACKUP
mkdir `date '+%d-%m-%Y'`
NOW=$(date +"%d-%m-%Y")

MUSER="root"
MPASS="mypass"
MHOST="sql4"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"

DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
 FILE=$BACKUP/$NOW/mysql-$db.$NOW-$(date +"%T").sql.gz
 $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS --lock-all-tables $db | $GZIP -9 > $FILE
done

How can I do this?

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

mysqldump will finish with exit code 0 if all went well. You can use that:

#!/bin/sh
BACKUP=/data/backup/sql2/new_backup/daily
cd $BACKUP
mkdir `date '+%d-%m-%Y'`
NOW=$(date +"%d-%m-%Y")

MUSER="root"
MPASS="mypass"
MHOST="sql4"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"
MAIL="youradress@example.com"
MAILER="$(which mail)"
STATUSFILE="/tmp/statusfile.$NOW"


echo "Backup report from $NOW" > $STATUSFILE
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
 FILE=$BACKUP/$NOW/mysql-$db.$NOW-$(date +"%T").sql.gz
 $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS --lock-all-tables $db | $GZIP -9 > $FILE
 if [ "$?" -eq "0" ] then; 
   echo "$db backup is OK" >> $STATUSFILE
  else 
   echo "##### WARNING: #####  $db backup failed" >> $STATUSFILE
  fi
done
$MAILER -s "Backup report for $NOW" -- $MAIL < $STATUSFILE
rm $STATUSFILE

I haven't tested this, but this is the general way to do it.

share|improve this answer
    
It should work, but I'd suggest use mail command, as mutt might be not installed, and mail is more common. Use something like cat $FILE | mail -s "subject" to@address1 to@addres2 –  rvs Apr 22 '11 at 9:20
    
In the first version I assumed that the dump file should be send by mail, and mail(x) can't send MIME attachments, AFAIK. In the second version, I use mail instead. –  SvW Apr 22 '11 at 9:29
    
Thanks a lot for you help. It worked! :) –  Saif Apr 23 '11 at 9:01
add comment
#!/bin/bash 

TO="email@example.org" 
SUBJECT="testmail"      
MSG="bla bla bla"

/usr/sbin/sendmail -t <<EOF
to:$TO
subject:$SUBJECT
$MSG
EOF

You can also add the "from" field, if necessary.

share|improve this answer
add comment

Your Answer

 
discard

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.