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:

set -u

mailSubject="Backup Successful"
mailTo="[email protected]"

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

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

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/ /opt/lampp/htdocs /opt/lampp/var/mysql"
try "scp /backup/xampp-backup-`date +%Y-%m-%d`.tar [email protected]:/backup/xampp/"
try "ssh [email protected] '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"

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