How to Backup MySQL Database and Remove Old Backup Using Shell Script

Create backup script:

$ nano backup.sh

Paste this script:

#!/bin/sh
# Scripts to create mysql backup every half an hour

# Configuration value
mysql_host=”localhost”
mysql_database=”ruko”
mysql_username=”ruko”
mysql_password=’123′
backup_path=/home/ruko/public_html/backup
expired=60 # delete backup files older than 60 days (2 months)

today=`date +%Y-%m-%d`
sql_file=$backup_path/${mysql_database}`date +_%Y-%m-%d_%H-%M`.sql

# Create backup directory if not exists
if [ ! -d “$backup_path” ]; then
mkdir -p “$backup_path”
fi

# Create MySQL dump
/usr/bin/mysqldump -h “$mysql_host” -u “$mysql_username” -p”$mysql_password” “$mysql_database” > “$sql_file”

# Compress backup
gzip “$sql_file”

# Remove backup files older than 60 days
find “$backup_path” -type f -name “*.gz” -mtime +$expired -exec rm -f {} \;

Save the file, and exit nano by press CTRL-X.

Run the backup script:

$ sh backup.sh

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.