Search code examples
bashgitgithooksshebang

Conditional shebang for Git hooks cross platform


In our projects we have developers who use windows and some use linux. We have githooks which uses shebang pointing to local windows shell executor, for example:

#!C:/Program\ Files/Git/usr/bin/sh.exe

REGEX_ISSUE_ID="[a-zA-Z0-9,\.\_\-]+-[0-9]+"
BRANCH_NAME=$(git symbolic-ref --short HEAD)
ISSUE_ID=$(echo "$BRANCH_NAME" | grep -o -E "$REGEX_ISSUE_ID")
LAST_COMMIT_MSG=$(git show -s --format=%s)

As you can see the shebang is pointing to the windows folder. This would never work for linux users. Is there a better way of handling this to work cross platform?


Solution

  • at least for the top level git hook script (.git/hooks/pre-commit for example), git for windows will interpret the #!/bin/sh shebang and use a bash interpreter for the script.

    if you then write posix-shell-compatible code in that script, it will be portable between windows and other posixly-correct machines

    in my experience, writing posixly-correct shell is a bit of a pain so I conditionally install that script with #!/usr/bin/env bash on other platforms and #!/bin/sh on windows source

    I'd then recommend explicitly calling out to other scripts as appropriate (python, etc.)