Created
April 30, 2023 11:25
-
-
Save holly/4d672a676efc8edcbb0ead034fd46616 to your computer and use it in GitHub Desktop.
wordpress backup script for rental server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -e | |
# default variables | |
BACKUP_DIR=$HOME/backup | |
AWSCLI=/usr/local/bin/aws | |
WPCLI=/usr/local/bin/wp | |
DATE=$(date +%Y%m%d%H%M%S) | |
ROTATE=3 | |
_wpdomain() { | |
$WPCLI --path=$WP_INSTALL_DIR option get siteurl | perl -nle '/^https?:\/\/([^\/]+)\/?.*/; print $1' | |
} | |
backup() { | |
local backup_dir=$BACKUP_DIR/$DOMAIN/$DATE | |
if [[ ! -d $backup_dir ]]; then | |
mkdir -p $backup_dir | |
fi | |
# wordpress contents backup | |
tar -C $WP_INSTALL_DIR -pczf $backup_dir/wordpress.tar.gz ./ | |
# wordpress mysql backup | |
$WPCLI --path=$WP_INSTALL_DIR db export - | gzip >"$backup_dir/mysqldump.sql.gz" | |
# delete old backup | |
while true; do | |
if [[ $(ls -1 $BACKUP_DIR/$DOMAIN | wc -l) -le $ROTATE ]]; then | |
break | |
else | |
local old_remove_dir=$(ls -t1 $BACKUP_DIR/$DOMAIN | tail -1) | |
rm -fr "$BACKUP_DIR/$DOMAIN/$old_remove_dir" | |
sleep 1 | |
fi | |
done | |
} | |
backup_s3() { | |
local s3cmd=$AWSCLI | |
if [[ -n "$AWS_PROFILE" ]]; then | |
s3cmd="$s3cmd --profile=$AWS_PROFILE" | |
fi | |
s3cmd="$s3cmd s3" | |
if [[ ! -d "$BACKUP_DIR/$DOMAIN" ]]; then | |
echo "[ERROR] "$BACKUP_DIR/$DOMAIN" is not exists." | |
exit 1 | |
fi | |
local target="" | |
if [[ -n "$REMOTE_TARGET" ]]; then | |
target=$REMOTE_TARGET | |
else | |
target=$(ls -t1 $BACKUP_DIR/$DOMAIN | head -1) | |
fi | |
for f in $(ls "$BACKUP_DIR/$DOMAIN/$target"); do | |
$s3cmd cp "$BACKUP_DIR/$DOMAIN/$target/$f" s3://$AWS_S3_BUCKET/$DOMAIN/$target/$f | |
done | |
} | |
cron() { | |
$WPCLI --path=$WP_INSTALL_DIR cron event run --due-now | |
} | |
if [[ $# -eq 1 ]] && [[ $1 =~ ^(backup|backup_s3|cron|restore)$ ]] ; then | |
MODE=${BASH_REMATCH[1]} | |
else | |
echo "Usage: $0 [backup|backup_s3|cron|restore]" | |
exit 1 | |
fi | |
if [[ -f "$HOME/wp.env" ]]; then | |
source "$HOME/wp.env" | |
fi | |
if [[ -n "$ENVIRONMENT" ]]; then | |
source "$HOME/wp.env.$ENVIRONMENT" | |
fi | |
if [[ ! -d $WP_INSTALL_DIR ]]; then | |
echo "[ERROR] $WP_INSTALL_DIR is not exists." | |
exit 1 | |
fi | |
if [[ ! -f $WP_INSTALL_DIR/wp-login.php ]]; then | |
echo "[ERROR] $WP_INSTALL_DIR: wordpress is not installed." | |
exit 1 | |
fi | |
DOMAIN=$(_wpdomain) | |
$MODE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment