Automating WordPress Backups with a Shell Script

In the digital age, data is invaluable, especially for websites that rely on content management systems like WordPress. Regular backups are essential to safeguard your website against data loss due to various reasons, including server failures, malware attacks, or accidental deletions. In this post, we’ll walk through a shell script designed to automate the backup process for a WordPress site, ensuring you have secure copies of your database and files.

Why Backup Your WordPress Site?

Backups serve as your safety net. They allow you to quickly restore your site to a previous state in case of issues. Here are some key reasons to regularly back up your WordPress site:

  • Data Loss Prevention: Accidental changes or deletions can happen. A backup allows you to revert to a working version.
  • Malware Recovery: If your site gets compromised, having a clean backup is crucial for recovery.
  • Server Failures: Hardware or software failures can lead to data loss. Backups ensure you can restore your site.

The Backup Script

Here’s a breakdown of a simple yet effective backup script for a WordPress site:

#!/bin/bash

# 1: Define backup filenames with timestamps.
db_backup_name="wp-db-backup-$(date +%d-%m-%Y-%H.%M).sql.gz"
wpfiles_backup_name="wp-content-backup-$(date +%d-%m-%Y-%H.%M).tar.gz"

# 2: Database connection info.
db_name="wordpress"
db_username="wordpress"
db_password="wordpress123"

# 3: Path to WordPress root directory and wp-content.
wp_root_folder="/var/www/html/wordpress"
backup_folder_path="/home/mahesh/backups/wordpress"

# 4: Backup MySQL database.
mysqldump --opt -u"$db_username" -p"$db_password" "$db_name" | gzip > "$backup_folder_path/$db_backup_name"

# 5: Navigate to WordPress root and create a tarball of wp-content only.
cd "$wp_root_folder" || exit
tar -czf "$backup_folder_path/$wpfiles_backup_name" wp-content

# 6: Delete all but 3 most recent database backups.
find "$backup_folder_path" -maxdepth 1 -name "*.sql.gz" -type f -printf "%T@ %p\n" | sort -rn | awk 'NR>3 {print $2}' | xargs -r rm --

# 7: Delete all but 3 most recent wp-content backups.
find "$backup_folder_path" -maxdepth 1 -name "*.tar.gz" -type f -printf "%T@ %p\n" | sort -rn | awk 'NR>3 {print $2}' | xargs -r rm --

Download the Script: gist.githubusercontent.com/maheshpalamuttath/482f1e43bc170d822fc4b19f368cd655/raw/8e2e96e40b2159aece20b6a0143f9383723b8317/wp-backup.sh

Breakdown of the Script

1. Defining Backup Filenames
The script starts by defining the names for the backups with a timestamp, ensuring that each backup is uniquely named. This prevents any accidental overwriting of existing backups.

db_backup_name="wp-db-backup-$(date +%d-%m-%Y-%H.%M).sql.gz"
wpfiles_backup_name="wp-content-backup-$(date +%d-%m-%Y-%H.%M).tar.gz"

2. Database Connection Information
Next, the script defines the database connection information, including the database name, username, and password. This allows the script to connect to the MySQL database to create a backup.

db_name="wordpress"
db_username="wordpress"
db_password="wordpress123"

Security Note: It is advisable to avoid hardcoding sensitive information directly into scripts. Consider using environment variables or a configuration file that has restricted access.

3. Specifying Directories
The paths to the WordPress root directory and the backup location are specified. This ensures that the script knows where to look for the files to back up and where to store the backup files.

wp_root_folder="/var/www/html/wordpress"
backup_folder_path="/home/sasc/backups/mahesh/wordpress"

4. Backing Up the MySQL Database
The mysqldump command creates a backup of the WordPress database, compressing it with gzip to save space. The output is redirected to a file named based on the current timestamp.

mysqldump --opt -u"$db_username" -p"$db_password" "$db_name" | gzip > "$backup_folder_path/$db_backup_name"

5. Creating a Tarball of wp-content
The script changes the directory to the WordPress root and creates a tarball of the wp-content directory, which contains all your themes, plugins, and uploaded files.

cd "$wp_root_folder" || exit
tar -czf "$backup_folder_path/$wpfiles_backup_name" wp-content

6. Cleaning Up Old Backups
To manage disk space, the script includes commands to delete old backups, keeping only the three most recent database backups and wp-content backups.

find "$backup_folder_path" -maxdepth 1 -name "*.sql.gz" -type f -printf "%T@ %p\n" | sort -rn | awk 'NR>3 {print $2}' | xargs -r rm --
find "$backup_folder_path" -maxdepth 1 -name "*.tar.gz" -type f -printf "%T@ %p\n" | sort -rn | awk 'NR>3 {print $2}' | xargs -r rm --

To set up this backup script on your server to run at regular intervals, you can use cron, the default job scheduler on Linux. Here’s a step-by-step guide:

Save your backup script with a .sh extension in a location that you can access. For example:

sudo su
vim /usr/local/bin/wp_backup.sh

Copy the script into this file, save it, and exit.

Give the script execute permissions so it can run:

chmod +x /usr/local/bin/wp_backup.sh

Run the script manually to ensure it works as expected:

/usr/local/bin/wp_backup.sh

If there are any errors, they should show up now, and you can troubleshoot as needed.

Use cron to automate the backup process. To edit the cron jobs:

crontab -e

Add a new line at the end of the file to specify when you’d like the backup to run. For example, to run the backup script every day at 2:00 AM, add this line:

0 2 * * * /usr/local/bin/wp_backup.sh >> /home/sasc/logs/wp_backup.log 2>&1

This command means:

0 2 * * * - Run at 2:00 AM every day.
/usr/local/bin/wp_backup.sh – Path to your backup script.
>> /usr/local/bin/logs/wp_backup.log 2>&1  – Save output and errors to a log file for troubleshooting.

If you’re using a log file, create a directory for it (Optional):

mkdir -p /usr/local/bin/logs

After adding the cron job, you can verify it with:

crontab -l

Your backup script is now set to run automatically on your server specified interval!

Use Rclone for Synching backup files into Google Drive: https://libtechnophile.blogspot.com/2020/07/using-google-drive-on-debianubuntu-with.html

Automating your WordPress backups with a shell script is a practical solution to ensure your data is safe and easily restorable. By regularly running this script, you can avoid the headaches of data loss and keep your site secure. Remember to periodically check your backup files and test the restoration process to ensure everything works as expected.

 

Using UpdraftPlus plugin for WordPress backup

Backing up our WordPress website is not a tedious task nowadays, several easy methods are there to backup, You can have your website backup either manually using any control panel of your server or setting up a bash script, or even using the WordPress plugins. Via plugin is the easiest and apt way for nontechies.

In the following video, I demonstrate how to install a wonderful plugin “UpdraftPlus”, configure, and how to schedule auto backup to Google Drive cloud storage, apart from Google Drive, UpdraftPlus offers you to sync with Amazon S3, Dropbox, Rackspace, Microsoft OneDrive, etc

All the WordPress plugins that I use!

WordPress Plugins are PHP scripts that extend the functionality of WordPress. They enhance the features of WordPress or add entirely new features to your site. Plugins are often developed by volunteers and are usually free to the public. Plugins are available via the WordPress Plugin Directory. All you want is just go to WordPress dashboard –> Plugins –> Add New –> search plugins from “Search Plugins” Searchbar click install then Activate the plugin

Here  are the WP plugins that I use

Akismet Anti-Spam

Akismet is quite possibly the best way in the world to protect your blog from spam

Classic Editor and Classic Widgets

This plugin disables Gutenberg editor totally everywhere and enables Classic Editor & Classic Widgets. Once activated, this plugin hides all functionality available in the new Gutenberg block editor. Also, you will be able to use old-style Classic Widgets under Appearance > Widgets and Appearance > Customize > Widgets. There is no need to set up any configuration.

Click to Chat

This plugin makes your Web page visitors contact you through WhatsApp with a single click/tap

Easy Table of Contents

Adds a user-friendly and fully automatic way to create and display a table of contents generated from the page content.

Image and video gallery from Google Drive

A WordPress gallery using Google Drive as file storage

Jetpack

WordPress security, performance, marketing, and design tools — Jetpack is made by WordPress experts to make WP sites safer and faster, and help you grow your traffic.

Yoast SEO

Yoast’s mission is SEO for Everyone. Our plugin’s users range from the bakery around the corner to some of the most popular sites on the planet. Yoast SEO Free contains everything that you need to manage your SEO

UpdraftPlus

A most wanted plugin, (I have already set up an auto backup of my WP files and database using a script) UpdraftPlus simplifies backups and restoration. Backup into the cloud directly to Dropbox, Google Drive, Amazon S3

Ninja Forms

Ninja Forms is a web form builder with unparalleled ease of use and features.

SlideShare

A plugin for WordPress to easily display slideshare.net presentations.

TablePress

Embed beautiful and feature-rich tables into your posts and pages, without having to write code.

WP Mail SMTP

For making email deliverability easy for WordPress

WP Popups Lite

Beginner-friendly WordPress popup builder plugin.

Secure Copy Content Protection and Content Locking

Secure Copy Content Protection is a plugin aimed at protecting web content from being plagiarized.

NB: Plugins can only be installed and used if you either self-host your WordPress or use a WordPress.com Business Plan

Reference: https://wordpress.org/support/article/managing-plugins/