This is a simple backup script in bash, for WordPress on Linux. It is based on the script from Small WordPress backup script post.
Like the script there it will dump MySQL database used by WordPress site and create a tar.gz file that will have WordPress site files and database dump.
This script will also send out an email if the backup process fails on any stage and delete old backups files.
#!/bin/bash bkpDir=/local/backup/directory webroot=/wordpress/install/directory/ bkpAge=90 #How many days of backup to keep dbUser=$(grep DB_USER $webroot/wp-config.php | awk -F\' '{print$4}') dbName=$(grep DB_NAME $webroot/wp-config.php | awk -F\' '{print$4}') dbPassword=$(grep DB_PASSWORD $webroot/wp-config.php | awk -F\' '{print$4}') dbDump="$bkpDir""$dbName"_$(date +'%F_%H_%M').sql rUser=remoteuser rHost=remoteserver rDir=/remote/backup/directory/ rSSHport=22 email="user@example.tld" errorFile="$bkpDir"errors rm -f "$errorFile" mysqldump -u $dbUser -p$dbPassword $dbName > $dbDump || echo "$(date +'%F %T') MySQL backup of $dbName failed." >> "$errorFile" tar -czf "$bkpDir"srvfail_$(date +'%F_%H_%M').tar.gz $webroot $dbDump || echo "$(date +'%F %T') Tar process failed." >> "$errorFile" rsync -az $bkpDir -e "ssh -p $rSSHport" $rUser@$rHost:$rDir --delete || echo "$(date +'%F %T') rsync to $rHost failed." >> "$errorFile" rm -f "$bkpDir"*$(date -d "$bkpAge days ago" +'%F')* if test -f "$errorFile"; then cat "$errorFile" | mail -s "Backup process on $(hostname) failed" "$email" fi
It will create two backup files, one for database dump in format that looks like “dbname__2021-12-01-06-00.sql” and one tar.gz file that will look like “wpbackup_2021-12-01_06-00.tar.gz”.
Script can be saved as wpbackup.sh and put in crontab to run at a certain time like 6:00AM.
0 6 * * * /path/to/script/wpbackup.sh >/dev/null 2>&1
or if you want to have output of it in case of errors
0 6 * * * /path/to/script/wpbackup.sh > /var/log/wpbackup.log 2>&1