Home > Backup, Linux, Opensource > Very Simple Backup script for Database and Files

Very Simple Backup script for Database and Files

April 24th, 2008

Hi,

This post will show you a simple way to take automatic DB backup and Files backup.

Warning: Not for Windows users :-)

When you are setting up backups its always good idea to save them on different server (atleast on different disk / disk partition)

Here are the steps to install this script

create a file

cat > /root/mycrons/backup.sh

now copy paste following script

## ——– Begin—————–

# Set a Date stamp to append to backup file
DATE=`date +%Y-%m-%d`
# DB Backup Dir
DBBACKUP=”/mnt/backups/db”
# Set Databas USER
DBUSER=”user”
# set DB password
DBPASS=”password”
#set DB Host
DBHOST=”localhost”
#list db names one per line in this file
DBLIST=”/mnt/backups/db/list.txt”
#set Location to store File backups
FILEBACKUP=”/mnt/backups/files”
# We will take WEBROOT directory backup
WEBROOT=”/opt/lampp/htdocs”
#add the excluded files/directory one per line in the this file.
# to know more about exclude option please check tar manual for –exclude-from #patterns
EXCLUDE=”/mnt/backups/files/exclude.txt”

for DBNAME in `cat $DBLIST`
do
# directory for each DB
FILEDIR=”$DBBACKUP/$DBNAME”

# create DB directory for the first time
if [ ! -d $FILEDIR ]
then
mkdir -p $FILEDIR
fi

mysqldump -h $DBHOST –user=$DBUSER -p$DBPASS –opt $DBNAME | gzip -c -9 > $FILEDIR/$DBNAME-$DATE.sql.gz

done

# Auto Delete
# Find all files that are “MaxAge” days old and delete them.
MaxAge=4
find $DBBACKUP -name ‘*.gz’ -type f -mtime +$MaxAge -exec rm -f {} \;

tar -zcf $FILEBACKUP/ufomusic_$DATE.tgz –exclude-from=$EXCLUDE $WEBROOT
find $FILEBACKUP -name ‘*.tgz’ -type f -mtime +$MaxAge -exec rm -f {} \;

## ——– End—————–

Now press ctrl + d to save the file. Before saving the script you need to change the parameters defined in the begining of script:

make the file executable

chmod u+x /root/mycrons/backup.sh

now add an entry to the crontab file to run this script on daily basis

59 23 * * * /root/mycrons/backup.sh

Thats it… this script will run on everyday at 23:59 and take the backup of DB and your Webroot directory . This script also delete the backup files which are older than MaxAge . You can set the MaxAge parameter value in the above script.

You can add n number of databases to the file defined in DBLIST parameter. all db will be dumped on daily basis.

For directories.. the logic is opposite. Define a root directory in WEBROOT and add the subdirectory names, you want to exclude in backup, in file defined in EXCLUDE variable.

–Asif–

editor Backup, Linux, Opensource

  1. No comments yet.
  1. No trackbacks yet.

Powered by Yahoo! Answers