Bash Script Example That Backs Up Your WordPress Site Using `rsync`

This is an example bash script that performs a backup using rsync. This script will sync files from a remote server to a local folder, ensuring that only updated files are transferred. It will also exclude common WordPress files and folders, as well as git version control files and folders.

Here’s a sample script:

#!/bin/bash

# Configuration
REMOTE_USER="your_remote_user"
REMOTE_HOST="your_remote_host"
REMOTE_PATH="/path/to/remote/wordpress/"
LOCAL_PATH="/path/to/local/backup/"

# Rsync options
RSYNC_OPTIONS="-avz --delete --update"

# Exclusion list for common WordPress files and git-specific files
EXCLUDE_LIST=(
    "wp-config.php"
    "wp-content/cache/*"
    "wp-content/backups/*"
    "wp-content/upgrade/*"
    "wp-content/uploads/*"
    "wp-content/uploads/backupbuddy_backups/*"
    ".git/*"
    ".gitignore"
		".git"
)

# Form the rsync exclude parameters
EXCLUDES=""
for e in "${EXCLUDE_LIST[@]}"; do
    EXCLUDES+=" --exclude=$e"
done

# Rsync command
RSYNC_CMD="rsync $RSYNC_OPTIONS $EXCLUDES $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH $LOCAL_PATH"

# Print the command (for debugging purposes)
echo "Executing command: $RSYNC_CMD"

# Execute the rsync command
eval $RSYNC_CMD

# Print completion message
echo "Backup completed successfully!"

Key Components:

  1. Configuration Section: Update REMOTE_USER, REMOTE_HOST, REMOTE_PATH, and LOCAL_PATH with your details.
  2. Rsync Options: Includes standard options for archive mode (-a), verbosity (-v), compression during transfer (-z), deletion of files that no longer exist on the source (--delete), and update (--update to skip files that are newer on the receiver).
  3. Exclusion List: List of files and directories to exclude, such as common WordPress files and git-specific files.
  4. Rsnyc Command Construction: Constructs the rsync command with all necessary options and exclusions.
  5. Execution and Output: Executes the constructed rsync command and prints a completion message.

Execution:

  1. Save the script to a file, for example, backup.sh.
  2. Make the script executable:
    chmod +x backup.sh
    
  3. Run the script:
    ./backup.sh
    

This script will help you maintain a local backup of your WordPress files from a remote server, without overwriting the local files that are already up to date, while respecting the exclusions.