Simple bash backup-tool

in script •  5 years ago 

If you only need a simple solution for backups using bash, you can handle it also in an easy way with encryption.
Feel free to apply any modifications you like or rebuild it to whatever you want ;)

#!/bin/bash

RCPT_KEY=YOUR_KEY_HERE
MAIL=YOUR_MAIL_HERE

mount -a
sleep 10
hosts_to_do=$(cat /etc/offsite_backup/vhosts.list)
for line in $hosts_to_do ; do
    DATE=`date +%Y-%m-%d`

    mkdir -p /var/offsite_backup_pre/backup_vhosts/$line/$DATE
    mkdir -p /var/offsite_backup/backup_vhosts/$line/
    # I use a file to define if my vhost has got a database
    DB=$(grep ^$line /etc/offsite_backup/dbconfig | awk '{print $2}')

    # If encryption is wanted for that vhost, it can be defined in that file
    ENC=$(grep ^$line /etc/offsite_backup/want_enc | awk '{print $2}')

    # copy content to remote system or locally
    rsync -avzH /var/www/$line/ /var/offsite_backup_pre/backup_vhosts/$line/$DATE/ 2>&1

    # check if DFB exists
    if [ "$DB" != "" ]; then
        mkdir -p /var/offsite_backup_pre/backup_vhosts/$line/$DATE/DATABASE_BAK
        mysqldump $DB > /var/offsite_backup_pre/backup_vhosts/$line/$DATE/DATABASE_BAK/$DB.sql
    else
        echo "no DB found"
    fi

    # compress files
    tar -czf /var/offsite_backup_pre/backup_vhosts/$line/$DATE.tar /var/offsite_backup_pre/backup_vhosts/$line/$DATE >/dev/null 2>&1

    # encrypt files if it is wanted
    if [ "$ENC" = "true" ]; then
        gpg --encrypt -a --recipient $RCPT_KEY /var/offsite_backup_pre/backup_vhosts/$line/$DATE.tar
        rm -rf /var/offsite_backup_pre/backup_vhosts/$line/$DATE.tar
        echo "$line [enc]" >> /tmp/backuplist
    else
        echo "$line" >> /tmp/backuplist
    fi

    # remove the pre-folder created during backup
    rm -rf /var/offsite_backup_pre/backup_vhosts/$line/$DATE/
done

# move files to final location
for line in $hosts_to_do ; do
    mv /var/offsite_backup_pre/backup_vhosts/$line/* /var/offsite_backup/backup_vhosts/$line/
done

# cleanup
rm -rf /var/offsite_backup_pre
DONE_BACKUPS=$(cat /tmp/backuplist)

# send status and clean status file
echo -e "Backups done for \n$DONE_BACKUPS" | mail -s "Backup finished" $MAIL
rm /tmp/backuplist

Additionally you normally want to remove old backups in different cycles.
Here is also a way to do so

#!/bin/bash
MAIL=YOUR_MAIL_HERE
retention=$(grep "" /etc/offsite_backup/vhosts_retention.list | awk  '{print $1}')
for line in $retention ; do
        if [[ $line != \#* ]]; then
                TIME=$(grep ^$line /etc/offsite_backup/vhosts_retention.list | awk  '{print $2}')
                find /var/offsite_backup/backup_vhosts/$line/* -mtime +$TIME -exec rm {} \;
        fi
done
echo -e "Following retention file has been issued\n$retention" | mail -s "Old backups removed" $MAIL
exit 0
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!