Bash Script to Sync WordPress Blog to Live Server

By | September 22, 2016

It’s handy to have a test server that we can use to see what will happen when we upgrade WordPress, install new plugins, or mess around with the layout and design of our blog. But how can we copy the changes we make to our test WordPress site to our live server? In this post, you will learn how to write a bash script to automate the synchronization of a test WordPress site to a live server.

There are two main things to consider when keeping a WordPress blog synchronized with another server:

  • The WordPress files and directories
  • The WordPress database

The script is broken down into four steps, and it allows you to run all of them in a row or do one at a time.

Let’s take a look at the entire script and then break it down into steps.

The entire script

Step 1: Export local test database

In the first step, we export a copy of our test server’s WordPress database. We use SSH to log in to the server and issue the mysqldump command to export the database to a directory.

Step 2: Synchronize files and directories

In step two, we use the command rsync to synchronize any changes to the website’s files with the live site. We start with a “dry run” of rsync, which shows up what changes will be made without actually doing anything. If we’re happy with the results, we can proceed with the real sync by simply removing the –dry-run option. Note the –exclude-from option in the rsync command. Here we can exclude files that we don’t want to upload to the production server. For example, wp-config.php, which contains server specific settings.

Check out my post on how to learn more about rsync and its options.

Step 3: Synchronize databases

In step three, we take the database file we exported in step one and copy it to the live server using rsync again.

Step 4: Import database into production server

In the final step, we import the database file which we exported from the test server.

After completing all four steps, the live server will be in sync with the test server.

Leave a Reply

Your email address will not be published.

*