#!/bin/bash
# Configuration
SITE_NAME="ScriptWP" # Used in backup filename
WP_PATH="/var/www/scriptwp.com" # Path to your WordPress installation
BACKUP_DIR="$HOME/wp-backups"
# Timestamp
NOW=$(date +"%Y-%m-%d_%H-%M-%S")
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
# Navigate to WordPress directory
cd "$WP_PATH" || { echo "❌ Error: WP path not found"; exit 1; }
# Export the database using WP-CLI
wp db export "$BACKUP_DIR/${SITE_NAME}_db_$NOW.sql" --quiet
# Create tar.gz archive including files and DB dump
tar -czf "$BACKUP_DIR/${SITE_NAME}_backup_$NOW.tar.gz" . "$BACKUP_DIR/${SITE_NAME}_db_$NOW.sql"
# Remove the raw SQL dump
rm "$BACKUP_DIR/${SITE_NAME}_db_$NOW.sql"
echo "✅ Backup complete: $BACKUP_DIR/${SITE_NAME}_backup_$NOW.tar.gz"
How to Create and Execute This Script
Follow these steps to create and run your WordPress script:
Open Your Terminal
Connect to your server via SSH or open your local terminal.
Create the Script File
Use a text editor like nano to create a new file. For example:
$ nano my-script.sh
Paste the Script Code
Copy the full script from above and paste it into the terminal. Once done:
- Press CTRL+O to save
- Press Enter to confirm the filename
- Press CTRL+X to exit nano
Make the Script Executable
$ chmod +x my-script.sh
Run the Script
$ ./my-script.sh
Requirements
- WP-CLI must be installed and accessible from the shell.
- wp-config.php must be correctly configured (WP-CLI uses it to access the DB).
- Run this script as a user with permission to access the WP directory and write to the backup folder.