A Simple Linux Shell Script To Export WordPress MySQL Database

One of the earlier posts explained how to backup WordPress databases directly through the Linux Terminal.

Here is an example of a simple shell script that will ask for the password of MySQL user that has access to the particular WordPress MySQL database to be exported and  dump it into the the directory specified . (To know what are Linux shell scripts and how to make them, please refer to the basic shell scripting tutorials we have) :

#!/bin/sh

# Demonstrated for fun by ihaveapc.com

TS=$(date +"%F")
DBBKPNAME="blog-$TS.sql"
mysqldump yourdatabasename -uusername -p > "/srv/dbdump/$DBBKPNAME"

TS is how the date format is stored for the database exported, in this case it will be YYYY-MM-DD format. This is then appended to prefix “blog” (can be the name of WordPress blog/domain name for clarity) and entire format is stored in DBBKPNAME which is what the exported database will look like in the specified directory (/srv/dbdump) in this case.

Copy the above script in a text editor like nano, vi etc and replace yourdatabasename and username as needed (These should be MySQL database and user names). Then save it as something meaningful like wpdb_exp.sh

Make the shell script executable by using :

chmod a+x wpdb_exp.sh

Finally, run it using :

./wpdb_exp.sh

Example :

avp@optimusprime[~/scripts]# ./testdb_exp.sh
Enter password:
avp@optimusprime [~/scripts]# ls /srv/dbdump/

./ ../ blog-2013-08-30.sql

So when this script is run on different days, different versions of WordPress databases will be exported and stored (depending on the dates) and these can be maintained as backups.

Isn’t this better and quicker then to remember the long export database command? :)

Cheers.

Leave a Comment