Bash: A very basic folder and MySQL bash backup script.

Here is a basic bash script to backup a folder and a MySQL database.

#!/bin/bash
#Backup script for www and mysql.

DATE=`date +%-Y%-m%-d`
backup_path="/path/to/where/iwant/mybackup/stored/"
backup_source="/path/of/myfolder/iwant/to/backup/"
user="db_username"
password="db_password"
host="db_host"
db_name="db_name"


# The function to actually do the backup.
function dobackup {
	echo "Starting backup for" $user
	echo "Backing up" $backup_source
	tar -cvzPf $backup_path$DATE-$user.tar.gz $backup_source
	echo "Backing up MySQL database.."
	mysqldump --user=$user --password=$password --host=$host $db_name > $backup_path/$db_name-$date.sql
	gzip $backup_path/$db_name-$date.sql
	echo "Backup done"
}

# Script should be run with arguement dobackup if we want to backup or delete if we want to delete todays backup.
if [ $1 = "dobackup" ] ; then
	dobackup
elif [ $1 = "delete" ] ; then
	rm -f $backup_path$DATE-$user.tar.gz
  	echo "Deleted old backup"
fi

Then we crontab this accordingly.

Alternatively you could add something like this to delete files older than 2 days on the backup path.

#Delete files older than 2 days
find $backup_path/* -mtime +2 -exec rm {} \;

#backup, #bash-2, #mysql, #script