Date created: Sunday, June 19, 2011 12:35:32 PM. Last modified: Sunday, January 27, 2019 11:45:38 AM

Try Example

A script to backup Xampp wrapped it in a 'try' system which passes each step of the backup process to a 'try' function (where each step of the backup process is a command to run) and if any step (command) should fail it will change the final email notification to say there was problem during the backup process.

This will show where in an automated task things are going wrong without stopping the. Adding 'set -e' would cause the script to exit if at anypoint a command failed but if in this example, the Xampp web server is stopped and then tar operation fails, it is important to carry on and start the web service again so that production is not affected.

The 'set -u' is just there for good practice; the script will stop if the user tries to use any uninitialised variables:

#!/bin/bash
set -u

mailSubject="Backup Successful"
mailTo="mailbox@domain.tld"
mailMessage="/tmp/backup_tmp"
failMail=0

echo "Backup: `date +%Y-%m-%d`" > $mailMessage

function try {
        result=`$1`
        if [ $? -ne 0 ]; then
                echo "error with: $1"
                mailSubject="Backup Failure"
                echo "error with: $1" >> $mailMessage
                echo "$result" >> $mailMessage
                failMail=1
        fi
}

try "/etc/init.d/xampp stop"
try "tar -cf /backup/xampp-backup-`date +%Y-%m-%d`.tar /opt/lampp/etc/my.cnf /opt/lampp/etc/httpd.conf /opt/lampp/etc/php.ini /opt/lampp/phpmyadmin/config.inc.php /opt/lampp/htdocs /opt/lampp/var/mysql"
try "scp /backup/xampp-backup-`date +%Y-%m-%d`.tar user@host:/backup/xampp/"
try "ssh user@host 'find /backup/xampp -maxdepth 1 -type f -mtime +29 | xargs rm'"
try "/etc/init.d/xampp start"
try "rm /backup/xampp-backup-`date +%Y-%m-%d`.tar"

#Uncomment to only send an email when there is a problem
#if [ $failMail -eq "1" ]; then
        cat $mailMessage | mail -s "$mailSubject" "$mailTo"
#fi

Previous page: Stuck In Time
Next page: Web Backup Scripts