Git hooks on Windows

On Unix/Linux, a Git hook script has a special #! (called “shebang”) first line that is used to indicate which program should run the script. On Windows, normally the special shebang first line has no effect (as it’s treated as a comment). However, Git on Windows is able to recognize the shebang first line. Therefore, we add a shebang line in a Git hook script on Windows just as we do on Linux. Below are two Git commit-msg hooks that run on Linux and Windows respectively.

Git commit-msg hook example on Linux

#!/bin/sh

# This example just print "commit-msg" when you executes a commit.

echo 'commit-msg';
exit 0;

Git commit-msg hook example on Windows

If you are using Git for Windows, the bash script also works on Windows.

#!/bin/sh

# This example just print "commit-msg" when you executes a commit.

echo 'commit-msg';
exit 0;

If you still have problems, try below, but this script is not portable on other machines if the their bash locations are different with .

#!C:/Program Files (x86)/Git/bin/sh.exe

# This example just print "commit-msg" when you executes a commit.

echo 'commit-msg';
exit 0;

The first line indicate using Git’s shell to run the script.

A PHP Git hook example on Windows

If you want to write a hook in other languages like PHP or Python, just specify the language in the first line as below example. It is a commit-msg Git hook in PHP, it checks the commit message length, if it exceeds 52 then reject the commit.

Remember to add PHP to your PATH location.

#!/usr/bin/env php

<?php
/**
 * Check the commit message length, if it exceeds 52 then reject the commit.
 */

// Note the commit-msg hook's three arguments starts from index of 1.
// The first argument $argv[0] is the script file itself.
$msg_file = $argv[1];
$contents = file_get_contents( $msg_file );
$commit_msg = strstr( $contents, "n", true ); // First line in commit msg file.
if( strlen(  $commit_msg ) > 52 ) {
    echo "Commit message format error: The length of commit message '$commit_msg' exceeds 52.";
    exit( 1 );
}
exit( 0 );

Save the content in above example in a file named commit-msg and put it in your git repository’s .git/hooks directory. Then you’ll see the effect by running the below command.

# The option --allow-empty allows an empty commit containing only a commit message.
$ git commit --allow-empty -m 'test commit-msg hook which checks the lenght of commit message'

Commit message format error: The length of commit message 'test commit-msg hook which checks the lenght of commit message' exceeds 52.

Leave a Reply