git: automatically run bash script ON THE SERVER after any client pushes

3.7k Views Asked by At

I have looked and found all sorts of git hook guides, but none seem to fit this specific, simple scenario.

I have my own server that I push code changes to (with git push origin master). After I do this, I have to ssh into the server and run a function that I have setup, "update-code", that clones the repo, runs ant, & restarts tomcat, etc. I want git to run this 'update-code' command for me after any user has run 'git push' (from their machine, not the server).

To recap, after any user pushes to my repo (from their machine), a shell command is automatically executed on the server the same way it would be if I were logged in and typed 'update-code'. What are the exact steps to have git do this?

3

There are 3 best solutions below

0
AlBlue On

You want to use a post-receive hook (see man githooks for details):

post-receive

   This hook is invoked by git-receive-pack on the remote repository,
   which happens when a git push is done on a local repository. It
   executes on the remote repository once after all the refs have been
   updated.

   This hook executes once for the receive operation. It takes no
   arguments, but gets the same information as the pre-receive hook does
   on its standard input.

Note that if multiple references are updated in the same push, this is only called once. If you need to be called and take action on different references (i.e. do one thing for master and another thing for release/) then you should look at the post-update hook instead.

These would be stored on your remote server, in the foo.git/hooks/ directory. Make sure that these scripts are executable.

0
Ôrel On

You can find a tutorial here: Automatic Deployment with Git

You need to create a script named post-receive into the hooks directory of you git repository (server side).

Don't forget to set the executable permission on your script chmod +x post-receive

1
kristakis On

I found this didn't work correctly until I set the first line of the post-receive file to #!/bin/sh

Wanted to tell someone has it took me a long time to figure out this was why it wasn't working.