Skip to main content

Create a hook to publish on push in GIT

GIT is now a very widely used source control platform, used across many different languages. There are many ways to use it and it has some great features.

One of those features is hooks, hooks are scripts that are fired at specific events in the GIT process. Today I will show you how to setup a hook that automatically pushes your changes to the public directory.

This is useful if you're working on a remote machine or you just want your process of migrating changes to a test server to be more efficient.

Create a bare repo

On your remote machine (server) you want to create a base for your bare repos and create a new repo for the project.

cd /usr/local/share/
mkdir gitrepos
cd gitrepos
mkdir myprojectname.git
cd myprojectname.git
git --bare init
chown username.usergroup -R /usr/local/share/gitrepos/myprojectname.git

Create the hook

Now that the repo has been created we can create a hook for GIT to execute whenever changes are pushed to the remote repo. You should set the working tree to be where the site is hosted.

// setup hook to move to web dir
cd /usr/local/share/gitrepos/myprojectname.git/hooks
vi post-receive

Insert the following into the file and save

GIT_WORK_TREE=/home/username/public_html/myprojectname git checkout -f

Now we want to make the hook executable. chmod +x post-receive

Push to publish

Finally on your local machine, setup a new repo within your project folder and set its remote to the bare repo you created on the remote machine.

cd /myprojectname
git init
git add .
git commit -m "Initial setup"
git remote add origin remote ssh://
git push origin master

Now whenever you push to the remote repo, your site will be automatically updated!