Menu
in ,

WordPress Database Auto Backup Using Linux Crontab And Bash Script

wordpress database backup

WordPress database backup is a very important task to care about, and as we talk in the previous post, we need to stop adding extra plugins to our WordPress and need to keep it as light as possible, you can read: Optimize WordPress Database Daily Using Linux Crontab

Each task can be separated away from WordPress, and transferred to the system side it will be a good action to apply.

WordPress Database Backup Policy

We need to apply the following backup policy

1- Take a database backup daily

2- Backup time will be at 1 AM

3- Remove Backup files older than 3 days.

And you can adjust your backup policy as you need, then implement it in the bash script like the following…

Database Backup Bash Script

We create a new  backup.sh  file, insert the script as shown with the description, and replace each bold green value with yours.

#!/bin/bash

# Database credentials
## Add database username
db_user="DBUSER"
## Add database password
db_password="DBPASSWORD"
## Add database server Hostname or IP Address
db_host="HOST-IP-ADDRESS_OR_HOST-NAME"
## Add database name
db_name="DBNAME"

# Backup path
db_backup_path="/root/mysqldb_backups"
current_date=$(date +"%d-%b-%Y")

# Dump the database
/usr/bin/mysqldump --user=$db_user --password=$db_password --host=$db_host $db_name > $db_backup_path/$db_name-$current_date.sql

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

Crontab The Database Backup Script.

Enable your script file for execution, then open the crontab command for edit

# chmod +x backup.sh
# crontab -e

And append the database backup script at the end as the following to run daily at 1 AM.

0 1 * * * /full/path/to/backup.sh >/dev/null 2>&1

Any way to adjust your script running date-time with crontab, you can use the Crontab.guru tool.

Leave a Reply

Exit mobile version