Easy Syncing of GitHub Pages

I’ve started using GitHub more and more recently as I’m finding Git’s steep learning curve, as compared to SVN, outweighed by GitHub’s usefulness and flexibility. One of those factors is GitHub’s “Pages” feature. From the docs:

The GitHub Pages feature allows you to publish content to the web by simply pushing content to one of your GitHub hosted repositories.

For example, I’ve recently started a repo to begin adding the many miscellaneous tests, POCs and demos I create during the course of development. Instead of requiring someone to download the repo just to see the examples, I use GitHub Pages to host the rendered version (when applicable). The “Mimicking Links” page is the first one I’ve published.

GitHub makes this automatic when you create a branch of your master named gh-pages. Any time you push to gh-pages, the results are published. Easy enough, but I quickly realized that I needed a way to mirror all changes on master in gh-pages without constantly having to type:

git checkout gh-pages
git merge master
git push origin gh-pages
git checkout master

Some quick searching turned up Oli Studholme’s helpful post “GitHub Pages and deleting git’s master branch”. He outlines his own attempts (and suggestions from the comments) and what finally worked for him. Since he had more requirements (deleting the master branch), I wanted to post exactly what I’ve ended on.

First, create your local repo and add it to GitHub.

From the command line, navigate into the root of your repo and run following block of code as referenced in the “Project Pages” section of the GitHub Pages docs (make sure you have no changes waiting to be committed):

git symbolic-ref HEAD refs/heads/gh-pages
rm .git/index
git clean -fdx

Now that your working directory is clean, merge in the master branch and push gh-pages to GitHub:

git merge master
git push origin gh-pages

You can now visit the url http:username.github.com/yourRepo/ to view the results (the first push may take a little time to show your changes).

Now that your pages are in place, you’ll want to automate the merging[1] to gh-pages any changes you commit in master.

To do this, open the post-commit.sample file located in yourRepo/.git/hooks and replace its contents with the following, saving it as post-commit:

#!/bin/sh
# Mirror master in gh-pages
git checkout gh-pages
git merge master
git checkout master

This block will run after every commit you make to the master branch (you’ll see the output on the command line).

All that’s left to do is push both branches to GitHub any time you’ve made a commit:

git push --all

I’m still pretty new to Git/GitHub, so any suggestions or corrections are appreciated.


  1. Oli’s post suggests rebase, but I’m sticking with merge as I understand it better.  ↩