Bash Script To Backup Folders and Databases using a Cron Job

I sometimes find I need a simple script to backup one or multiple folders and databases. This script just takes a list of pre-defined folders and databases, compresses the folder contents, and executes a database dump. A maximum of seven backups are kept, any older ones are deleted.

Customize the first six variables as needed.

#!/bin/bash

#set folders/dbs to loop through
folderarr="folderone foldertwo folderthree"
dbarr="dbone dbtwo dbthree"

#set db username and pass
dbuser="dbuser"
dbpass="dbpass"

#backupfolder
backupfolder="/home/username/backup"
projectfolder="/home/username/public_html"

echo "starting backup"

logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt
echo "mysqldump started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"

#ensure all directories exist
for day in 1 2 3 4 5 6 7
do
	mkdir -p "$backupfolder"/backup"$day"
done

#delete oldest backups and move rest in reverse order
rm -f "$backupfolder"/backup7/*
mv "$backupfolder"/backup6/* "$backupfolder"/backup7/
mv "$backupfolder"/backup5/* "$backupfolder"/backup6/
mv "$backupfolder"/backup4/* "$backupfolder"/backup5/
mv "$backupfolder"/backup3/* "$backupfolder"/backup4/
mv "$backupfolder"/backup2/* "$backupfolder"/backup3/
mv "$backupfolder"/backup1/* "$backupfolder"/backup2/

#backup all folders as separate tarballs in backup-one
for dbname in $folderarr
do
	echo "Processing project: $dbname"

	now="$(date +'%d_%m_%Y_%H_%M_%S')"

	#backup file folder
	tar -cvpzf "$backupfolder"/backup1/"$dbname"-files-"$now".tar.gz "$projectfolder"/"$dbname"

	echo "backed up project $dbname" >> "$logfile"
done

#backup all folders as separate tarballs in backup-one
for dbname in $dbarr
do
	now="$(date +'%d_%m_%Y_%H_%M_%S')"

	#backup database
	filename="$dbname"-db-"$now".sql.gz
	fullpathbackupfile="$backupfolder"/backup1/"$filename"

	#dump database
	mysqldump --user="$dbuser" --password="$dbpass" --default-character-set=utf8 "$dbname" | gzip > "$fullpathbackupfile"
	echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"

	find "$backupfolder" -name db_backup_* -mtime +8 -exec rm {} \;
done

echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"

exit 0