Dez Futak's Development Blog

Dez Futak's Development Blog>Backup Databases>SMB Share>Backup Databases>SMB Share

This little bash script uses WP CLI to backup your databases to an SMB share. Obviously, you can hack it to change the destination, or even integrate with something like

Please use this at your own risk (ie, I'm not liable if something goes wrong!).

There's probably way more elegant ways to do this by the way, so feel free to improve on the coding...

#timestamp the created files
now=`date +%Y-%m-%d-%H-%M-%S`

#find each Wordpress root directory and save it to a temporary file
find /home -name wp-config.php| rev | cut -c14- | rev > wpath.txt
wpath=(`cat wpath.txt`)

#Create temporary backup location for databases in this time-snapshot
mkdir -p $tmpbackups

#Define the 3-day local backup directory (quicker than copying via smb share)

#Define the smb share location for the 8-day backups

#Loop round & backup databases via the wp cli command
for d in "${wpath[@]}"
#postpend each saved file with a suitable name
web=(`echo $d| cut -c7- |sed 's/\/.*//'`)

/usr/local/bin/wp --allow-root --path=$d db export $tmpbackups/wp-mysql-$web-temp.sql; /usr/bin/zip $tmpbackups/wp-mysql-$web-$ $tmpbackups/wp-mysql-$web-temp.sql; /usr/bin/rm -rf $tmpbackups/wp-mysql-$web-temp.sql


rm -rf wpath.txt

#Store databases locally for further redunancy
cp -a $tmpbackups/* $localbackups/

#Delete local backups older than 3 days
cd $localbackups; find . -mtime +3 -exec rm {} \;

#Backup latest databases to smb share
/bin/tar cfz $smb/$now.tgz $tmpbackups

#Delete databases in temporary location to preserve filesystem space
rm -rf  $tmpbackups
#Delete backup files on smb share older than 8 days
cd $smb; find . -mtime +8 -exec rm {} \;

I'm sure you can improve on this, so do feel free to share your more elegant solution.

Share this