captaincore/lib/remote-scripts/db-backup
2026-03-15 11:06:14 -04:00

52 lines
No EOL
1.9 KiB
Bash

#!/usr/bin/env bash
#
# Backup database to a private directory
#
# Store current path
home_directory=$(pwd)
private_directory=""
# Find private folder
if [ -d "_wpeprivate" ]; then
private_directory=${home_directory}/_wpeprivate
fi
if [ -d "../private" ]; then
cd ../private
private_directory=$(pwd)
cd $home_directory
fi
if [ -d "../tmp" ]; then
cd ../tmp
private_directory=$(pwd)
cd $home_directory
fi
if [[ "$private_directory" == "" ]]; then
echo "Can't find private folder. Database backup cancelled.";
exit 1
fi
# get the wp-config.php variables
database_name=$( wp config get DB_NAME --skip-plugins --skip-themes )
database_username=$( wp config get DB_USER --skip-plugins --skip-themes )
database_password=$( wp config get DB_PASSWORD --skip-plugins --skip-themes )
# Check if mysqldump supports --no-tablespaces (added in 5.7.31 / 8.0.21)
no_tablespaces_flag=""
if mysqldump --no-tablespaces --version &>/dev/null; then
no_tablespaces_flag="--no-tablespaces"
fi
# Perform DB backup with [emoji support](https://anchor.host/wp-cli-database-backups-with-emojis/) and [speed](https://guides.wp-bullet.com/how-to-export-large-wordpress-databases-and-speed-up-the-process/)
# Try with --single-transaction first for InnoDB consistency, fall back without it if FLUSH TABLES privilege is missing
if ! mysqldump -u ${database_username} -p${database_password} --max_allowed_packet=512M --default-character-set=utf8mb4 --add-drop-table --single-transaction --quick --lock-tables=false ${no_tablespaces_flag} ${database_name} > ${private_directory}/database-backup.sql 2>/dev/null; then
mysqldump -u ${database_username} -p${database_password} --max_allowed_packet=512M --default-character-set=utf8mb4 --add-drop-table --quick --lock-tables=false ${no_tablespaces_flag} ${database_name} > ${private_directory}/database-backup.sql
fi
# Make it safe
chmod 600 ${private_directory}/database-backup.sql