Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Git Hooks: pre-commit, commit-msg, and Husky Automation

Hooks live in .git/hooks, which a clone never receives, so core.hooksPath and Husky are how they travel. Exit codes abort the operation, and every hook is bypassable.

~5 min readGit
#Git#Hooks#Husky#Automation
3D illustration of commit blocks rolling through check gates on a conveyor before a commit tray

Quick Summary

A Git hook is an executable script that Git runs at a fixed point in its own workflow: before a commit is created, after it is created, before a push leaves, when a checkout finishes. Client hooks live in .git/hooks/, which is not part of the repository, so a fresh clone has none of them — only *.sample files.

That single fact explains the tooling. Husky points core.hooksPath at a committed directory, so hooks travel with the code; lint-staged keeps pre-commit fast by running linters only on staged files; commitlint validates the message in commit-msg, which is the only hook that sees the final text.

Exit codes are the contract: a non-zero exit from pre-commit, commit-msg, pre-push, or pre-rebase aborts the operation; post-* hooks run after the fact and their exit codes are ignored. Every hook is bypassable (--no-verify, HUSKY=0), so hooks are a convenience for the author, never a guarantee for the repository.

Basic Syntax and Core Signatures

bash
# What Git calls, and when pre-commit # before the commit message editor; abort = non-zero prepare-commit-msg # $1 message file, $2 source (message|template|merge|squash|commit), $3 sha commit-msg # $1 message file; validate or rewrite it post-commit # after the commit exists; cannot abort pre-push # $1 remote name, $2 remote url, refs on stdin; abort = non-zero pre-rebase # $1 upstream, $2 branch being rebased post-checkout # $1 old HEAD, $2 new HEAD, $3 flag (1 = branch checkout) post-merge # $1 squash flag post-rewrite # $1 amend|rebase, rewritten pairs on stdin pre-receive # server-side: all refs on stdin, reject with non-zero update # server-side: one ref at a time post-receive # server-side: after acceptance, cannot reject
bash
# A hook you write yourself mkdir -p .git/hooks cat > .git/hooks/pre-commit <<'SH' #!/bin/sh set -e npx lint-staged SH chmod +x .git/hooks/pre-commit # Make hooks part of the repository git config core.hooksPath .githooks # Git 2.9+ git commit -m "chore: track hooks" # Husky 9 npm install --save-dev husky npx husky init # creates .husky/, sets core.hooksPath=.husky/_ echo "npx lint-staged" > .husky/pre-commit echo 'npx --no -- commitlint --edit "$1"' > .husky/commit-msg

Husky 9 removed the #!/usr/bin/env sh and . "$(dirname -- "$0")/_/husky.sh" boilerplate that v8 required; the files in .husky/ are plain shell scripts today, and husky install is replaced by husky init. Old guides that paste the v8 wrapper still work in v8 only.

Key Comparison Table

HookRunsCan abortSees the messageTypical use
pre-commitBefore the message is writtenYesNolint-staged, type check, secret scan
prepare-commit-msgBefore the editor opensYesYes, editableTicket id from branch name
commit-msgAfter the editor closesYesYes, final textConventional commits, trailers
post-commitAfter the commit existsNoYesNotifications, cache warmup
pre-pushBefore objects transferYesNoFull test suite, build
post-checkoutAfter checkout/switchNoNoDependency install, env files
pre-receiveOn the server, per pushYesNoBranch protection, policy
Distribution methodTravels with cloneSurvives npm ciWorks in CI unasked
.git/hooks/* by handNoNoNo
core.hooksPath + committed dirYes, after git configYesNo
HuskyYes, via prepare scriptYesOnly if core.hooksPath is set
Server hook (pre-receive)N/AN/AYes, for everyone

Practical Edge Cases and Deep Dives

1. Why the hook "does not run"

bash
ls -l .git/hooks/pre-commit # -rw-r--r-- 1 ryu staff 42 ... <- not executable: silently skipped chmod +x .git/hooks/pre-commit head -1 .git/hooks/pre-commit # #!/bin/sh <- missing shebang: exec format error, or ignored

Three causes cover most reports: the file is not executable, it has no shebang, or it is pre-commit.sample (which Git never runs — the .sample suffix disables it). A fourth is Windows: hooks run through Git's bundled sh, so a CRLF-terminated script fails with a cryptic bad interpreter — set core.autocrlf correctly for hook files and keep them LF.

2. pre-commit and commit-msg need the same file from different states

commit-msg receives $1 = path to the message file. It must be read, not parsed from git log. With Husky 9, quote the argument:

bash
# .husky/commit-msg npx --no -- commitlint --edit "$1"

prepare-commit-msg gets the same path plus a source: message (given with -m), template, merge, squash, or commit (during --amend, with the original sha in $3). Prepending a ticket id only makes sense for message and merge, so guard on $2 — otherwise amend and interactive rebase produce mangled subjects.

3. lint-staged, the stash, and partially staged files

json
{ "lint-staged": { "*.{ts,tsx}": ["eslint --fix --max-warnings=0", "prettier --write"], "*.md": "prettier --write" } }

lint-staged stashes everything not staged, runs the commands against the staged content, re-adds the results, then restores the stash. That is why editing a file heavily and staging only part of it can produce a conflict when the stash is restored — the hook aborted mid-restore and your unstaged work is in git stash list. --no-stash disables the mechanism (and lets a partial commit capture unintended changes). On a large repository the fix is scope, not speed: match fewer globs, and let the CI run the full suite.

4. pre-push runs on every push attempt, including rejected ones

bash
# .husky/pre-push #!/bin/sh set -e npm run typecheck npm run test -- --runInBand

pre-push fires on git push and again on git push --force-with-lease, and its cost is paid before any network round trip. On a branch pushed frequently this is the hook people disable. Two adjustments keep it useful: read the refs from stdin and skip the work when the push only deletes branches, and put the expensive suite behind an env flag ([ "$SKIP_SLOW" = "1" ] && exit 0) that the author consciously sets.

5. Hooks are local, so CI must duplicate them

bash
git commit --no-verify -m "wip" # skips pre-commit and commit-msg HUSKY=0 git push # Husky-specific escape hatch

Anything a hook enforces is enforceable only by the same check running on the server. The pattern that holds is: local hooks for speed and formatting, CI for the authoritative check, and a server-side hook or branch protection for the rules that must never be broken. A team that relies on commit-msg alone will eventually merge a message that bypassed it, because --no-verify exists and is not rare.

6. Server-side hooks and the policy they can actually enforce

bash
# .git/hooks/pre-receive on the receiving repository (bare, shell access needed) #!/bin/sh while read old new ref; do case "$ref" in refs/heads/main) if [ "$old" != "0000000000000000000000000000000000000000" ] && ! git merge-base --is-ancestor "$old" "$new"; then echo "main is fast-forward only" >&2 exit 1 fi ;; esac done

pre-receive sees every ref in one shot and can reject the whole push; update runs per ref and can only reject that ref. Both run with the server's environment, so a script that depends on node or a project-local binary will fail on a bare repository — and hosted providers (GitHub, GitLab) do not let you install hooks at all, offering branch protection rules instead. Server hooks are for self-hosted repositories; everywhere else the equivalent is a required status check.

Common Git Operation Mistakes

SymptomCauseFix
Hook silently skippedNot executable, or no shebangchmod +x, add #!/bin/sh
Hook works locally, missing after clone.git/hooks is not committedcore.hooksPath plus a committed directory
husky - command not found in CIDev dependencies not installed (npm ci --omit=dev)Install dev deps, or HUSKY=0 for jobs that do not need it
bad interpreter: No such fileCRLF line endings in the hookConvert to LF
Pre-commit takes 30sWhole-project lint instead of staged fileslint-staged with narrow globs
Commit message rule bypassed--no-verifyEnforce the same rule in CI or a server hook
Stash conflict after a commit attemptlint-staged stash restore clashed with editsgit stash list, resolve, --no-stash if needed
core.hooksPath ignoredOld Git, or a worktree with a relative pathGit 2.9+, absolute path
Hook changed the file but the commit missed itpre-commit edits are not re-stagedLet the tool re-add (lint-staged does), or git add -u

Try matching browser tools

All tools

Small utilities that fit Git work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Git guides

More in Git

All Git guides

The guides filed next to this one in Git, in library order.