Sub topic 3
How a Hook Runs: Executable Bit, Arguments and Exit Status
This chapter assumes you know the basic Git workflow (add, commit, push) and the difference between the staging area and the working tree. It also assumes you can read and write a short shell script. It covers the mechanics Git uses to find, start and judge a hook. Later chapters build real checks on top of these mechanics.
What Git does when it reaches a hook point
A hook is an ordinary file. When Git reaches a hook point, such as the start of git commit, it follows these steps:
- It looks in the hooks directory for a file whose name exactly matches the hook, for example
pre-commit. The directory is.git/hooksunlesscore.hooksPathpoints elsewhere. - If no such file exists, Git skips the hook and carries on.
- If the file exists but is not executable, Git skips it. Recent versions print a hint saying so.
- If the file is executable, Git starts it as a child process, passing any arguments that hook defines.
- Git waits for the process to end and reads its exit status.
- For hooks that can block an action, a non-zero status aborts the operation. A zero status lets it continue.
Notice that two failure modes are silent: a misspelled name and a missing executable bit both make Git skip your hook. Your check never runs, and the commit goes through as if the hook did not exist.
The executable bit
On Linux and macOS, a file runs only if its mode includes the execute permission. A file you create with an editor or a redirect usually gets mode 644, which has no execute bit. Git does not run it.
The .sample files that git init creates in .git/hooks are inert for the same reason. Their suffix means the name does not match any hook, and they are not executable.
The following commands show the effect. They create a repository with a hook that always rejects the commit, so you can see when it takes effect.
git init hook-demo
cd hook-demo
cat > .git/hooks/pre-commit <<'EOF'
#!/bin/sh
echo "pre-commit: rejecting everything" >&2
exit 1
EOF
echo hello > a.txt
git add a.txt
git commit -m "first"The commit succeeds. Git prints a hint that the pre-commit hook was ignored because it is not set as executable. Now set the bit and try again:
chmod +x .git/hooks/pre-commit
git commit -m "first"This time the hook runs, prints its message and exits with status 1. Git aborts with no new commit, and a.txt stays staged.
Tracking the bit in a repository
Git records a single permission bit per file: executable or not. When you share hooks from a tracked directory, the mode travels with the file in the commit. If a hook lost its bit, you can fix it in the index, even on a filesystem that does not support permissions:
git update-index --chmod=+x .githooks/pre-commitOn Windows with NTFS, the filesystem has no execute bit. Git for Windows runs hooks through its bundled sh, so the shebang line still matters there. Chapter 12 covers platform differences in more detail.
The interpreter: shebang lines
Git does not know what language your hook is written in. It executes the file, and the operating system decides how to run it. The first line, called the shebang, tells the system which interpreter to use:
#!/bin/shA hook can be written in any language: Python (#!/usr/bin/env python3), Ruby, Node.js, or a compiled binary with no shebang at all. For shell hooks, #!/bin/sh is the most portable choice. Use #!/usr/bin/env bash only if you need Bash features, and then make sure every teammate has Bash.
Some systems will still run a script that has no shebang by handing it to a shell. Do not rely on this. Always write the shebang, because it makes the interpreter explicit and keeps your hook portable.
The environment a hook sees
Git starts client-side hooks with these properties:
- Working directory: the root of the working tree. Relative paths such as
src/main.pyresolve from there, no matter which subdirectory you rangit commitin. - Environment variables: Git sets
GIT_DIR, and sometimes others. Do not clear them, because commands such asgit diff --cachedinside the hook use them to find the right repository. - Standard input:
pre-commitshould not assume it is connected to a terminal. If a hook must prompt the user, read from/dev/ttyexplicitly. Be aware that this breaks in editors and scripts that have no terminal. - Output: write messages to standard error with
>&2. Git generally forwards a hook's standard output to standard error for client-side hooks, but being explicit costs nothing and avoids surprises in tools that capture output.
Arguments: each hook has its own contract
Git passes arguments positionally, and every hook defines its own. A hook that reads $1 when Git passes nothing gets an empty string, and no error is raised. Check the documentation (git help githooks) for the hook you are writing.
| Hook | Arguments | Extra input | Non-zero status |
|---|---|---|---|
| `pre-commit` | none | none | aborts the commit |
| `prepare-commit-msg` | message file path, optional source, optional commit ID | none | aborts the commit |
| `commit-msg` | path to the file holding the proposed message | none | aborts the commit |
| `post-commit` | none | none | ignored |
| `pre-push` | remote name, remote URL | lines on standard input, one per ref being pushed | aborts the push |
| `post-checkout` | previous HEAD, new HEAD, branch-checkout flag | none | affects only the exit status of `git checkout` |
Two points follow from the table.
First, pre-commit receives no information about which files are being committed. If it needs the list, the hook must ask Git, for example with git diff --cached --name-only. The next chapters rely on that.
Second, pre-push receives its detail on standard input. Each line has the form <local ref> <local object name> <remote ref> <remote object name>. You read it with while read rather than from $1.
Observing the arguments
A small probe hook shows exactly what Git passes. This script installs one in three hook slots. Run it inside the hook-demo repository:
for h in pre-commit commit-msg pre-push; do
cat > ".git/hooks/$h" <<'EOF'
#!/bin/sh
echo "hook=$(basename "$0") args=$# first=${1-none} cwd=$(pwd)" >&2
exit 0
EOF
chmod +x ".git/hooks/$h"
done
mkdir -p sub
echo more > sub/b.txt
git add sub/b.txt
cd sub
git commit -m "probe"You should see two lines of output. The first reports hook=pre-commit args=0 first=none. The second reports hook=commit-msg args=1 first=.git/COMMIT_EDITMSG, which is the message file path. Both lines show a cwd ending in hook-demo rather than hook-demo/sub, even though you ran the commit from sub. That confirms the working directory rule.
Exit status decides the outcome
The exit status is the only signal Git reads from a blocking hook. Printed text does not matter, and neither does the content of any file the hook writes.
- Status
0means success. The operation continues. - Any other status from 1 to 255 means failure. Git aborts the operation. By convention, use
1. - A hook killed by a signal also counts as a failure.
Hooks that run after the fact (post-commit, post-merge, post-rewrite) cannot undo anything. Their status is ignored, or at most changes the exit status of the command that triggered them. Do not put checks there.
Pitfall: the status of the last command
A shell script's exit status is the status of the last command it ran, unless you call exit explicitly. This script looks like it blocks bad commits, but it does not:
#!/bin/sh
git diff --cached --check
echo "check finished"When git diff --cached --check finds problems, it returns non-zero. The script then runs echo, which succeeds, so the script exits with 0 and the commit goes through. Capture the status, or test the command directly:
#!/bin/sh
if ! git diff --cached --check; then
echo "pre-commit: whitespace problems found." >&2
exit 1
fiPitfall: pipelines
In a plain POSIX shell, a pipeline's status is the status of its last command. In check_files | sort, a failure in check_files is lost. Avoid piping the command whose status matters. Either write its output to a variable or file first, or use set -o pipefail in Bash.
Pitfall: `set -e` and loops
set -e makes a script stop at the first failing command, which is convenient for short hooks. It has exceptions: failures inside if conditions, && chains and || lists do not stop the script. When you want to run every check and report all failures, collect them in a variable instead:
#!/bin/sh
status=0
git diff --cached --check || status=1
test -z "$(git diff --cached --name-only -- '*.orig')" || { echo "remove .orig files" >&2; status=1; }
exit $statusThis pattern runs both checks, so the developer sees every problem in one attempt rather than one per commit.
Where bypassing fits in
Because a hook is an ordinary process that the committer's own Git launches, the committer controls it. git commit --no-verify (short form -n) skips pre-commit and commit-msg. git push --no-verify skips pre-push. Deleting the file or clearing its executable bit has the same effect. A later chapter covers this and explains why a CI check must back up any rule you care about.
Common mistakes
- Wrong file name.
pre-commit.sh,precommitandpre-commit.sampleare all ignored. The name has no extension. - Missing executable bit. The hook is skipped. Check with
ls -l .git/hooks. - Wrong or missing shebang. The system may fail with "bad interpreter", or run the script in a shell you did not intend.
- Windows line endings. A shebang written as
#!/bin/shfollowed by a carriage return makes the system look for an interpreter namedsh\r. Save hooks with LF endings. - Reading arguments the hook does not get.
pre-commithas no$1. - Forgetting an explicit
exit. The script returns the status of whatever ran last.
Exercise
A teammate's pre-commit hook ends with the lines grep -n "TODO" src/*.py and echo "done". Some commits contain no TODO, and the hook never blocks anything even when TODOs are present. Give two separate reasons the hook cannot block, and write the fix so it blocks the commit when a TODO is found in the staged version of any .py file.
Show answer
First, the hook's exit status is the status of the final echo, which is always 0, so Git always proceeds. Second, grep returns 0 when it finds a match and 1 when it does not, so even a bare grep at the end would block commits without TODOs, the opposite of the goal. The hook also reads the working tree rather than the staged content. A fix is: #!/bin/sh followed by if git diff --cached -U0 -- '*.py' | grep -q '^+.*TODO'; then echo "pre-commit: remove TODO comments." >&2; exit 1; fi and exit 0. Here grep -q finding a match makes the if true, and the explicit exit 1 blocks the commit.
Exercise
You run git commit from the subdirectory docs/ of a repository. In the pre-commit hook, which directory is the working directory, and how many positional arguments does Git pass? What argument does a commit-msg hook receive?
Show answer
The working directory is the root of the working tree, not docs/. pre-commit receives zero positional arguments. commit-msg receives one argument: the path to the file that holds the proposed commit message, typically .git/COMMIT_EDITMSG.
Exercise
You create .git/hooks/pre-commit with an editor, put exit 1 on its only line, and run git commit. The commit succeeds. List the checks you would make, in order, to find out why.
Show answer
Check that the file name is exactly pre-commit with no extension (ls .git/hooks). Check the mode with ls -l and run chmod +x if the execute bit is missing. Look for the "hook was ignored because it's not set as executable" hint. Check that the hooks directory is the one Git uses, by running git config core.hooksPath. If it prints a path, Git reads hooks from there instead of .git/hooks. Finally, check the first line for a valid shebang and LF line endings, then run the file directly (.git/hooks/pre-commit; echo $?) to confirm it exits with 1.