Home > Wiki > Git Articles

All articles are licensed under CC0 1.0 making them public domain.

Auto deploying to a webserver #

Last updated February 2021

Git on the server has mechanisms to run scripts when certain actions occur, these are called Git Hooks. The following is a setup using the post-receive hook to auto deploy the code in the Git repo to a directory elsewhere on the server. The destination directory is presumably the root of a web server location.

NOTE: This only applies to self-hosted Git servers, not services like GitHub.

post-receive Script

This file should be located at hooks/post-receive within the .git directory on the hosting server. It will only trigger on changes on master. Make sure you give the script execute permission too: chmod +x hooks/post-receive.

#!/bin/bash
while read oldrev newrev ref
do
  if [[ $ref =~ .*/master$ ]];
    then
      echo "Deploying changes to web server"
      git --work-tree=$HOME/Sites/example --git-dir=$HOME/example.git checkout -f
  fi
done