Git hooks

Intermediate · 6 min

Run your own scripts at key moments in Git: write pre-commit, commit-msg and pre-push hooks, share them via core.hooksPath, and why hooks aren't security.

Before thisWriting good commit messagesRefs, branches and HEAD

GitGuardian · 6 min

Git hooks

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by GitGuardianReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A hook is an executable file named after an event, such as `pre-commit` or `commit-msg`, that Git runs at that moment, and a non-zero exit from a `pre-` hook aborts the operation.
  • Local hooks live in `.git/hooks`, which is not part of the repository, so share them by committing a directory and setting `core.hooksPath` to it.
  • `commit-msg` receives the path of the message file as `$1`, and `pre-push` receives the remote name and reads the refs being pushed from standard input.
  • Hooks can be skipped with `--no-verify`, and a hook file that isn't executable is silently ignored, so hooks are conveniences and the real gate is checks on the server.
  • Git 2.54 can also run hooks defined in config with `hook.<name>.event` and `hook.<name>.command`, and `git hook list <event>` shows what will run.

Rules that live outside people’s heads

“Don’t commit FIXMEs.” “Keep commit subjects short.” “Make sure the script still parses before pushing.” Teams write rules like these down, and then people forget. A hook turns a rule into something Git runs for you at a precise moment.

A hook is just an executable file with a special name. When Git reaches that moment, such as before creating a commit, it looks for the file and runs it. For hooks whose name starts with pre-, a non-zero exit code stops the operation.

Look at what a new repository already contains:

$ ls .git/hooks
applypatch-msg.sample    pre-commit.sample      pre-rebase.sample
commit-msg.sample        pre-push.sample        prepare-commit-msg.sample
...

These .sample files are templates. Remove the suffix and make the file executable to activate one.

A pre-commit hook

I wanted to refuse commits that add a FIXME line to jot. This goes in .git/hooks/pre-commit:

#!/bin/sh
# refuse to commit staged lines that contain FIXME
if git diff --cached -U0 | grep -q '^+.*FIXME'; then
  echo "pre-commit: staged changes contain FIXME, fix it or commit with --no-verify" >&2
  exit 1
fi

Then chmod +x .git/hooks/pre-commit. The hook inspects what is staged (git diff --cached) because that is what the commit will contain.

$ echo "# FIXME handle empty list" >> jot.sh
$ git commit -am "Note a problem"
pre-commit: staged changes contain FIXME, fix it or commit with --no-verify
$ echo $?
1
$ git commit -q --no-verify -am "Note a problem"
$ git log --oneline
d40c157 Note a problem

The first commit was blocked. --no-verify skipped the hook. And when I removed the executable bit, Git didn’t complain loudly: it printed a hint (The '.git/hooks/pre-commit' hook was ignored because it's not set as executable) and the commit went through. If a hook “does nothing”, check chmod +x first.

commit-msg and pre-push

Other hooks receive arguments. commit-msg gets the path to the message file:

#!/bin/sh
subject=$(head -1 "$1")
if [ ${#subject} -gt 50 ]; then
  echo "commit-msg: subject is ${#subject} characters, keep it to 50 or fewer" >&2
  exit 1
fi

pre-push gets the remote name as $1, and on standard input, one line per ref being pushed: local ref, local hash, remote ref, remote hash.

#!/bin/sh
remote=$1
while read local_ref local_sha remote_ref remote_sha; do
  echo "pre-push: sending $local_ref to $remote ($remote_ref)" >&2
done
sh -n jot.sh || exit 1

sh -n parses a script without running it. I checked it by committing a deliberately broken jot.sh:

$ git commit -m "This subject line is much longer than fifty characters for sure"
commit-msg: subject is 63 characters, keep it to 50 or fewer
$ git push origin main
pre-push: sending refs/heads/main to origin (refs/heads/main)
jot.sh: line 9: syntax error near unexpected token `then'
error: failed to push some refs to '../hub.git'

Both hooks did their jobs. The first is the message-quality rule from writing good commit messages, enforced.

Sharing hooks with the team

.git/hooks isn’t versioned, so a clone gets only the samples. Put hooks in a normal folder, commit it, and point Git at it:

$ mkdir .githooks     # hooks go here, then: git add .githooks
$ git config core.hooksPath .githooks

I cloned the repository afterwards:

$ git clone hub.git c2
$ ls c2/.githooks
commit-msg
pre-push
$ git -C c2 config core.hooksPath
$

The scripts came along, but core.hooksPath is local config, so it came back empty and the hooks are inactive in the clone. Each person runs the config command once, usually from a setup script or the README. Tools such as pre-commit and Husky automate this install step.

Config-based hooks in Git 2.54

Git 2.54, which I ran, can also define hooks in configuration instead of files:

$ git config hook.lintcheck.event pre-commit
$ git config hook.lintcheck.command 'echo "config-hook ran" >&2'
$ git hook list pre-commit
lintcheck
$ git commit -qm "Add README"
config-hook ran

git hook list <event> shows what will run, including file hooks (it reported hook from hookdir for the core.hooksPath ones). I only tested this on 2.54, so check git --version before relying on it. Older Git has only file hooks.

Hooks are a convenience, not a lock

Every client-side hook can be bypassed: --no-verify, a missing install, a non-executable file. Use them for fast feedback, and put the same checks in CI, which is the next topic after Git itself, because that gate can’t be skipped. Server-side hooks (pre-receive, update) run on the remote and can enforce rules on pushes, but hosting services usually replace them with branch protection.

What the video covers

GitGuardian’s “What are GitHooks? Explained in 5 minutes” is about six minutes and was published around 2023. From its title and the channel’s focus on secret detection, it introduces hooks and, probably, their use for catching secrets. I judge English from the title, description and channel only, and I could not read a transcript, so I can’t confirm what it demonstrates. The Modern SDE’s lesson on all the main hooks is linked as a runner-up.

Where this fits

Hooks are one of the ways to customize Git. The rest of the customization surface, config, aliases and attributes, is next: configuration, aliases and attributes.

Check yourself

  1. 01Your `pre-commit` hook exists but never runs. What are the two most likely causes?

    The file isn't executable, so Git ignores it with a hint, or it has the wrong name or sits outside the directory set by `core.hooksPath`.

  2. 02Why aren't hooks in `.git/hooks` shared when someone clones the repository?

    The `.git` directory isn't versioned. Commit your hooks to a normal folder and have each person run `git config core.hooksPath <folder>`.

  3. 03How does a `commit-msg` hook read the message?

    Git passes the path of a file containing the message as the first argument, `$1`, so the hook reads that file and exits non-zero to reject it.

  4. 04Why shouldn't you rely only on client-side hooks to enforce a rule?

    Anyone can bypass them with `--no-verify` or by not installing them. Enforce important rules in CI or on the server too.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark