awesomeprogrammer.com

Sharing ideas

Solving problems

Gathering solutions

Exchanging thoughts

Ruby On Rails

PHP

Postgres

Debian & Ubuntu
jQuery & CSS

Git Deployment Using Post-receive Hook

Let’s assume you have configured your brand new git repository on a brand new server and now you want to setup it in a way that every push done on a master branch update your production directory. How can you achieve that?

You can use git hooks feature. In hooks/ directory in your git repo you can find a file called post-receive, take a look at quick example below:

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash

while read oldrev newrev ref
do
  branch=`echo $ref | cut -d/ -f3`

  if [ "master" == "$branch" ]; then
    git --work-tree=/YOUR-PRODUCTION-DIRECTORY-HERE/ checkout -f $branch
    echo 'Changed pushed to production'
  fi
done

What this script does is checking out repository to a specific directory (—work-tree) if this push was done on master branch. Of course you can add more stuff there, it’s just simple example but it works great (tested with git 1.5). Unfortunately I can’t remember where I found out about this solution, but the credit goes to the original author.

Also – don’t forget to add execute permission for that file (chmod +x post-receive).

Comments