Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 78 ยท Customizing and Automating Git

Git Hooks

Learn Git hooks with runnable examples: pre-commit, commit-msg, pre-push, post-merge and server-side pre-receive, core.hooksPath, git hook run, --no-verify and their limits.

A hook is a script that Git runs for you at a fixed moment: just before a commit is created, after a merge finishes, before a push leaves your machine. Hooks turn "please remember to run the linter" into "the commit does not happen until the linter passes". They are plain executable files, so you can write them in Bash, Python, Node or anything else that can start from a shell.

In this lesson you will write real hooks that run in the sandbox: one that blocks bad commits, one that enforces a message format, one that guards pushes, and a server-side hook that protects a shared branch. You will also learn the biggest hook limitation, which is that hooks are optional for the person using them, and how teams deal with that.

What a hook is and where it lives

When you run git init, Git creates .git/hooks/ and fills it with example files that end in .sample. Git ignores a file unless its name is exactly the name of a hook, with no extension, and it is executable. Remove .sample and chmod +x the file and the hook is live.

Bash The hooks directory and a first pre-commit hook

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The fresh repository contains 14 .sample files, none of them active. The first commit printed pre-commit: checking staged files and succeeded: the hook ended without an explicit exit, so its status was that of its last command, the if statement, which is 0 when its condition is false. (Add an explicit exit 0 at the end of real hooks so a later edit cannot change this by accident.) The rule Git uses is simple: an exit status of 0 lets the operation continue, any non-zero status aborts it. The second commit hit exit 1, so Git stopped after printing the refusal, and git log still showed only the first commit. Finally --no-verify (short form -n) told Git to skip the pre-commit and commit-msg hooks, so the third commit went through.

Hook output is shown on stderr, even what your script prints with plain echo. In a terminal you will not notice, but in a script that captures stdout you will. The examples here use 2>&1 so you can see the order.

The hooks you will actually use

Git has about two dozen hook names. Most teams use only a handful. Here they are, in the order a typical day triggers them.

Hook Runs Can it block? Typical use
pre-commit before the commit message is asked for yes lint, format check, forbid debug code, run fast tests
prepare-commit-msg after the default message is built, before the editor yes add a ticket number, a template
commit-msg after you wrote the message yes enforce a message convention
post-commit after the commit exists no notifications, local housekeeping
pre-rebase before a rebase starts yes stop rebasing published branches
post-checkout, post-merge after switching or merging no reinstall dependencies when lock files changed
pre-push after the remote is contacted, before objects are sent yes run the test suite, block pushes to main
pre-receive, update, post-receive on the server, when a push arrives pre-receive and update can enforce policy, trigger deployments

pre-merge-commit, applypatch-msg, pre-applypatch (for git am), reference-transaction and fsmonitor-watchman also exist; you can read what each is for in the .sample files and in git help hooks on a machine that has the manual pages.

Every hook gets information through arguments (for example the path of the message file for commit-msg), standard input (for example the refs being pushed) and environment variables such as GIT_DIR and GIT_INDEX_FILE. Always read the arguments rather than assuming files in the current directory; hooks run from the top of the working tree for client-side hooks and from the repository directory on the server.

Sharing hooks with core.hooksPath

Nothing inside .git/ is ever committed or cloned, so hooks in .git/hooks stay on your machine only. To share hooks with your team, put them in a tracked folder and tell Git to look there:

CONSOLE
git config core.hooksPath .githooks

The folder .githooks is committed like any other directory, and every contributor runs that one git config command once (often wired into a setup script or npm install). You can also set core.hooksPath globally to an absolute path to run the same hooks in every repository you own.

The next example uses it for a commit-msg hook. Git passes the path of the file that holds the message as the first argument.

Bash commit-msg hook with core.hooksPath

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first commit was rejected and nothing was recorded; your staged files stay staged, so you just retry with a better message. Notice that the hook does not use git log or any repository state: it only reads the message file, which makes it fast and easy to test. This is the same convention described in Making Good Commits.

When a hook rejects something, make the error message say what is wrong and how to fix it. People will meet your hook at their worst moment, in the middle of a commit.

Checking what will be committed, not what is on disk

A very common bug in pre-commit hooks is checking the working tree instead of the index. If you stage a file, then edit it again, the file on disk differs from what is about to be committed. A hook that reads the file on disk validates the wrong version. The fix is to read the staged content with git show :path (the colon means "from the index") and to list candidates with git diff --cached.

The same example also shows a post-merge hook, which cannot block anything but is useful for reminders such as "package-lock.json changed, run npm install".

Bash Check the staged version, and a post-merge hook

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first commit failed because the staged copy of a.txt still contained TODO, even though the file on disk no longer did. After git add a.txt the index matched the disk and the commit passed. The -z and -d '' options pass file names separated by NUL bytes, which keeps the loop correct for names with spaces. The merge of topic into main created a real merge commit, so post-merge ran and printed the squash flag 0.

Guarding pushes with pre-push, and templating messages

pre-push runs after Git has talked to the remote and before any objects are sent. It receives the remote name and URL as arguments and one line per ref on standard input: <local ref> <local sha> <remote ref> <remote sha>. That is enough to refuse pushes to certain branches, or to run your tests only when something is really about to leave your machine.

prepare-commit-msg receives the message file and the source of the message (message, template, merge, squash, commit). The hook below prefixes the message with a ticket id taken from the branch name, so feature/ABC-12 produces [ABC-12] ....

Bash pre-push, prepare-commit-msg and post-commit together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The commit message became [ABC-12] add a, because prepare-commit-msg ran after Git had built the message and before the commit was created. The post-commit line was printed to stderr, so we piped it through sed to hide the changing hash. The push of feature/ABC-12 printed the refs the hook read from stdin, then succeeded. The push to main was stopped by exit 1, and Git reported error: failed to push some refs. --no-verify skipped pre-push, and both branches now exist on the remote.

Server-side hooks

Client-side hooks help you. Rules that must hold for everyone have to run on the server, because a server hook cannot be skipped with --no-verify. Hosting services such as GitHub and GitLab expose this as branch protection and push rules, but on a plain Git server it is a file in the bare repository. pre-receive gets one line per ref on stdin (<old> <new> <ref>). If it exits non-zero, the whole push is rejected. The sandbox lets you try it with a local bare repository.

Bash A pre-receive hook that forbids force-pushing main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Normal fast-forward pushes passed, because the old tip is an ancestor of the new one (git merge-base --is-ancestor, see How Merge, Rebase and Diff Work Inside). The forced push replaced a commit, so the hook printed pre-receive: rewriting main is not allowed, Git answered [remote rejected] main -> main (pre-receive hook declined), and the remote history stayed untouched. Messages that a server hook writes to stderr arrive at the client with the prefix remote:. A server-side update hook runs once per ref and is easier when you want to accept some refs and reject others from the same push.

Running and managing hooks: git hook

Since Git 2.36, git hook run <name> runs a hook by hand with the exact environment Git would give it, which is perfect for testing. git hook list <name> shows which hooks Git would run. Recent Git versions (including the 2.56 used here) also allow hooks defined in configuration instead of files: hook.<name>.event says when it runs and hook.<name>.command is the command. Config hooks can come from system, global or local config, so a company can install shared hooks everywhere, and several hooks can listen to the same event.

Bash git hook run, git hook list and config-defined hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git hook run exited with 0 and printed the hook's greeting. The list showed hook from hookdir first, and after configuration also lint. When both exist the config hook ran first, then the file in the hooks directory, and both ran during the commit. If your team uses older Git versions, stick with files and core.hooksPath.

The limits of hooks

Be honest about what hooks are:

  • They are voluntary. --no-verify, a fresh clone before git config core.hooksPath is run, or simply deleting the file disables them. Enforce critical rules (tests, secret scanning, branch protection) in CI and on the server (GitHub Actions: CI for Your Repository); use client hooks for fast feedback only.
  • Keep them fast. A pre-commit hook that takes 30 seconds teaches people to use --no-verify. Check only staged files, and leave the full test suite for pre-push or CI.
  • Do not rewrite files silently. Auto-formatters in pre-commit that modify the working tree can leave the index and disk out of sync. If you must, format and re-git add the exact files that were staged, or just fail with a message telling the user to run the formatter.
  • They are scripts, so test them. Run git hook run, feed fake stdin to pre-push, and keep them small. A project at the end of this track builds a tested set of hooks: Project: Quality Gates with Hooks.
  • Tools exist. The pre-commit framework (Python), Husky and lint-staged (Node), Lefthook (Go) install hooks from a configuration file and manage tool versions. They are read-only here because they download tools and need a network, but under the hood they install the same files you just wrote.
  • Portability. A hook needs an interpreter on every machine. #!/bin/sh scripts work on Linux, macOS and Git for Windows (which ships its own shell); a Python hook needs Python installed.
  • Hooks are not copied by git clone and git init on an existing repository does not overwrite hooks that already exist.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which exit status makes Git abort the operation that triggered a blocking hook such as pre-commit?

    Zero means success and lets Git continue. Any non-zero status makes pre-commit, commit-msg, pre-push and pre-receive abort the operation.
  2. 2. Why do hooks in .git/hooks not reach your teammates when they clone the repository?

    The contents of .git (including hooks and config) are local. Commit your hooks in a normal folder and set core.hooksPath to it.
  3. 3. A pre-commit hook must validate the exact content that is about to be committed. Which command reads the staged version of a file?

    A colon before the path means 'from the index'. Reading the file on disk checks the working tree, which can differ from what is staged.
  4. 4. Which approach enforces 'nobody may force-push main' even for users who run git push --no-verify?

    --no-verify only skips client-side hooks. A pre-receive hook runs on the server and cannot be bypassed by the pusher.
  5. 5. What does the commit-msg hook receive as its first argument?

    Git writes the message to a file and passes its path, so the hook can read it (and even edit it) before the commit is created.

Summary

  • A hook is an executable file named exactly like the hook (no extension) in .git/hooks, or in the folder named by core.hooksPath. Exit status 0 continues, non-zero aborts the blocking hooks.
  • Client-side hooks: pre-commit, prepare-commit-msg, commit-msg, post-commit, post-merge, post-checkout, pre-push and more. Server-side: pre-receive, update, post-receive.
  • Share hooks by committing them to a folder and running git config core.hooksPath <folder>; recent Git versions (such as the 2.56 used here) also support hooks defined in config (hook.<name>.event and .command).
  • Check staged content with git diff --cached and git show :path, not the files on disk.
  • git hook run tests a hook by hand; git commit --no-verify and git push --no-verify skip client hooks.
  • Hooks give fast feedback but are not security. Enforce real rules on the server and in CI.

Next: .gitattributes, Line Endings and Large Files