Aniruddha Joshi
Aniruddha Joshi

Reputation: 133

Understanding Git Hook - post-receive hook

I have written simple shell script to throw "success and failure message" and placed it under .git/hooks/ with all proper permissions. I want to call this script as a post-receive. But the script is not working, running the script simply works but as post-receive hook it doesn't work.

Is their something being missed or have i wrongly understood the post-receive hook. Can some one explain client-side and server-side hooks and how to execute them.

I have searched over it but not able to understand.

Upvotes: 7

Views: 20742

Answers (2)

fitorec
fitorec

Reputation: 4775

To enable the post-receive hook script, put a file in the hooks subdirectory of your .git directory that is same named (without any extension) and make it executable:

touch GIT_PATH/hooks/post-receive
chmod u+x GIT_PATH/hooks/post-receive

For more info check this doc: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

Example

Check this example (a simple deploy) GIT_PATH/hooks/post-receive:

#!/usr/bin/env bash
TARGET="/home/webuser/deploy-folder"
GIT_DIR="/home/webuser/www.git"
BRANCH="master"

while read oldrev newrev ref
do
    # only checking out the master (or whatever branch you would like to deploy)
    if [[ $ref = refs/heads/$BRANCH ]];
    then
        echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
        git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f
    else
        echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
    fi
done

Source: https://gist.github.com/noelboss/3fe13927025b89757f8fb12e9066f2fa#file-

Upvotes: 14

VonC
VonC

Reputation: 1324977

It needs to be called post-receive (no extension, no post-receive.sh for instance).

If it is placed (as the OP did) in .git/hooks folder, and made executable, it will be called when you are pushing to that repo (since it is a server hook).
If you were to install it on your own local repo, it would not be called (unless you somehow push to your own repo, which seems unlikely).

For a remote Git hosting server like GitHub, you would need to implement that hook as a webhook (a listener to GitHub push event).

Upvotes: 3

Related Questions