Sub topic 1
What Git hooks are and where they live
A Git hook is a program that Git runs for you at a fixed point in its workflow. A hook can only be a file in a known location. Git finds it by name, runs it, and in some cases reads its exit status to decide whether to continue. This chapter explains what hooks are, which ones run on your machine, where Git looks for them, and why that location matters when a team wants to share them.
Prerequisites
This chapter assumes you already have the following:
- A working Git workflow: you can run
git add,git commitandgit pushwithout help. - Comfort with a command line and at least basic shell scripting (variables,
if, exit codes). - A clear picture of the staging area (also called the index) versus the working tree. The index holds what the next commit will contain. The working tree holds the files on disk.
You do not need to have written a hook before. Examples use POSIX sh, so they run on Linux, macOS and Git Bash on Windows.
What a Git hook is
Git is mostly a set of commands you call. Hooks reverse that for a few moments. When you run git commit, Git reaches certain points, such as "about to create the commit" or "message has been written", and looks for an executable file with a specific name. If the file exists, Git runs it. If it does not exist, Git carries on.
Three properties define the model:
- The file name is the hook name. A script called
pre-commitruns before a commit is created. A script calledmy-checknever runs, because Git does not know that name. - Any executable works. A hook can be a shell script, a Python script, a compiled binary, or a wrapper that calls something else. Git needs only a file it can execute. For scripts, the first line (the shebang, such as
#!/bin/sh) tells the operating system which interpreter to use. - The exit status can matter. For most hooks that run before an action, a non-zero exit status stops the action. For hooks that run after an action, the status is ignored, because the action has already happened.
This is why hooks suit pre-commit checks. A script that inspects your change and exits with a failure code can stop a bad commit before it exists.
Client-side and server-side hooks
Git splits hooks by where they run.
- Client-side hooks run on the machine of the person using Git. They fire during commits, merges, rebases, checkouts and pushes. This tutorial is about these hooks.
- Server-side hooks run on the machine that receives a push, such as a self-hosted Git server. They include
pre-receive,updateandpost-receive. You normally cannot install them in a hosted service such as GitHub. Those services offer their own mechanisms instead, such as branch protection rules and CI checks.
The distinction decides how much you can trust a hook. A server-side hook runs in an environment the repository owner controls. A client-side hook runs on each developer's computer, where the developer can edit, disable or skip it. Keep this in mind, because a later chapter in this tutorial covers why CI is still required.
Here are the client-side hooks you will meet most often:
| Hook | When Git runs it | Can it stop the action? |
|---|---|---|
| `pre-commit` | Before Git asks for a commit message | Yes |
| `prepare-commit-msg` | After the default message is prepared, before the editor opens | Yes |
| `commit-msg` | After you write the message, before the commit is created | Yes |
| `post-commit` | After the commit is created | No |
| `pre-rebase` | Before a rebase starts | Yes |
| `post-checkout` | After `git checkout` or `git switch` updates the working tree | No (the status becomes the command's exit status) |
| `post-merge` | After a merge completes | No |
| `pre-push` | After the remote is contacted, before objects are sent | Yes |
Git has more hooks than this table lists. The githooks manual page (git help hooks) is the complete reference for your installed version.
Where hooks live
By default, hooks live in the hooks directory inside the repository's Git directory. In an ordinary clone, that is .git/hooks.
ls .git/hooksIn a fresh repository you will usually see files such as pre-commit.sample and commit-msg.sample. Git copies these from its template directory when you run git init or git clone. The .sample suffix is deliberate. Git only looks for exact hook names, so a sample does nothing until you remove the suffix. Which samples you get depends on your Git version and installation.
Finding the directory Git actually uses
The default location can change, so do not assume .git/hooks. Ask Git:
git rev-parse --git-path hooksThis prints the directory Git will search. It respects the core.hooksPath setting described below, and it handles layouts where .git is not a directory.
The places hooks can live
| Situation | Hooks directory |
|---|---|
| Ordinary clone | `.git/hooks` |
| Bare repository (a server-side repository with no working tree) | `hooks` at the top of the repository directory |
| Linked worktree created with `git worktree add` | The main repository's hooks directory, shared by all worktrees |
| `core.hooksPath` is set | The directory named by that setting |
Redirecting with core.hooksPath
The core.hooksPath configuration variable tells Git to look in a different directory. This is the main reason it exists: you can point Git at a directory that is part of the project.
git config core.hooksPath .githooksA relative path is resolved from the directory where hooks run, which for most client-side hooks is the top of the working tree. When this setting is present, Git does not also run hooks from .git/hooks. It uses one directory or the other.
This setting is stored in .git/config, so it applies to your clone only. Another person who clones the project will not have it until they run the same command. A later chapter covers how teams handle that.
Why hooks are not shared by default
Git versions the contents of your working tree. It does not version .git. Whatever you put in .git/hooks stays on your machine. It is not committed, pushed or cloned.
This has two consequences:
- A teammate who clones the repository gets only the sample files, not the hooks you wrote.
- If you want the whole team to run the same check, the hook script must live somewhere that Git tracks, such as a
.githooksdirectory in the project. Each person must then point Git at it.
Try it: a hook that always fails
Before you write real checks, confirm that your Git installation runs hooks at all. This experiment uses a throwaway repository, so nothing important is affected.
mkdir hook-demo && cd hook-demo
git init
cat > .git/hooks/pre-commit <<'EOF'
#!/bin/sh
echo "pre-commit: the hook ran" >&2
exit 1
EOF
chmod +x .git/hooks/pre-commit
git commit --allow-empty -m "first commit"
echo "exit status: $?"You should see the message from the hook, and git commit should report no new commit. The echo line prints a non-zero status. The hook exited with 1, so Git aborted the commit.
Now change the last line of the hook to exit 0 and run the commit again:
sed -i.bak 's/^exit 1$/exit 0/' .git/hooks/pre-commit
git commit --allow-empty -m "first commit"The hook still prints its message, but the commit succeeds, because the exit status is zero. The -i.bak form keeps a backup file and works with both GNU and BSD sed. When you are done, leave the directory and delete hook-demo.
Two details in this demo are easy to miss. The message goes to standard error (>&2) so that it is visible even when a tool captures standard output. The chmod +x line sets the executable bit, which the next section explains.
Common problems with hook files
Most "my hook does nothing" reports come from a small set of causes.
- The file is not executable. Git requires the executable bit on Unix-like systems. In recent Git versions, a non-executable hook is skipped and Git prints a hint that it was ignored. Older versions may skip it silently. Fix it with
chmod +x. - The name is wrong.
pre-commit.sh,precommitandpre-commit.sampleare not hook names. The name must match exactly, with no extension. - The shebang is missing or wrong. Without a valid first line such as
#!/bin/sh, execution can fail with an "exec format error" or run under an unexpected shell. - Windows line endings. If the script was saved with CRLF line endings, the shebang line may be read as
/bin/sh\r, and the interpreter is not found. Save hook scripts with LF endings. - The hooks directory is not the one you think. If
core.hooksPathis set, in the repository, the user's global config or the system config,.git/hooksis ignored. Rungit config --show-origin core.hooksPathto see the value and where it came from. - You are in a different clone or worktree. Hooks you add to one clone do not appear in another.
What to carry forward
A hook is a correctly named, executable file in the directory Git searches. Pre-action hooks can block an operation through a non-zero exit status. Client-side hooks are local, which means they help each developer catch mistakes early but cannot guarantee anything about what reaches the server. The next chapters build on this model, starting with which client-side hooks fire and when, and then how Git passes arguments to them.
Exercise
You wrote a script at .git/hooks/pre-commit, ran chmod +x on it, and committed it to the repository with git add -f .git/hooks/pre-commit. Your teammate clones the repository and the hook does not run for them. Give two reasons this can happen and one way to confirm which directory their Git uses.
Show answer
Git does not track the contents of .git, so a clone does not receive files from .git/hooks, and the git add -f attempt would not have added a usable file there anyway. The teammate's .git/hooks contains only the default samples. Also, if the teammate has core.hooksPath set (for example in a global config), Git ignores .git/hooks entirely. To confirm, run git rev-parse --git-path hooks in their clone, and use git config --show-origin core.hooksPath to see whether the setting is defined and where. The fix is to keep the script in a tracked directory such as .githooks and have each person run git config core.hooksPath .githooks.
Exercise
A post-commit hook ends with exit 1. Does this undo or block the commit that just happened? Why or why not?
Show answer
No. post-commit runs after the commit has already been created, and Git ignores its exit status for the purpose of the commit. Only hooks that run before an action, such as pre-commit, commit-msg and pre-push, can stop that action with a non-zero exit.