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.

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
# 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# 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-msgHusky 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
| Hook | Runs | Can abort | Sees the message | Typical use |
|---|---|---|---|---|
pre-commit | Before the message is written | Yes | No | lint-staged, type check, secret scan |
prepare-commit-msg | Before the editor opens | Yes | Yes, editable | Ticket id from branch name |
commit-msg | After the editor closes | Yes | Yes, final text | Conventional commits, trailers |
post-commit | After the commit exists | No | Yes | Notifications, cache warmup |
pre-push | Before objects transfer | Yes | No | Full test suite, build |
post-checkout | After checkout/switch | No | No | Dependency install, env files |
pre-receive | On the server, per push | Yes | No | Branch protection, policy |
| Distribution method | Travels with clone | Survives npm ci | Works in CI unasked |
|---|---|---|---|
.git/hooks/* by hand | No | No | No |
core.hooksPath + committed dir | Yes, after git config | Yes | No |
| Husky | Yes, via prepare script | Yes | Only if core.hooksPath is set |
Server hook (pre-receive) | N/A | N/A | Yes, for everyone |
Practical Edge Cases and Deep Dives
1. Why the hook "does not run"
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 ignoredThree 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:
# .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
{
"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
# .husky/pre-push
#!/bin/sh
set -e
npm run typecheck
npm run test -- --runInBandpre-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
git commit --no-verify -m "wip" # skips pre-commit and commit-msg
HUSKY=0 git push # Husky-specific escape hatchAnything 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
# .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
donepre-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
| Symptom | Cause | Fix |
|---|---|---|
| Hook silently skipped | Not executable, or no shebang | chmod +x, add #!/bin/sh |
| Hook works locally, missing after clone | .git/hooks is not committed | core.hooksPath plus a committed directory |
husky - command not found in CI | Dev dependencies not installed (npm ci --omit=dev) | Install dev deps, or HUSKY=0 for jobs that do not need it |
bad interpreter: No such file | CRLF line endings in the hook | Convert to LF |
| Pre-commit takes 30s | Whole-project lint instead of staged files | lint-staged with narrow globs |
| Commit message rule bypassed | --no-verify | Enforce the same rule in CI or a server hook |
| Stash conflict after a commit attempt | lint-staged stash restore clashed with edits | git stash list, resolve, --no-stash if needed |
core.hooksPath ignored | Old Git, or a worktree with a relative path | Git 2.9+, absolute path |
| Hook changed the file but the commit missed it | pre-commit edits are not re-staged | Let the tool re-add (lint-staged does), or git add -u |
Try matching browser tools
All toolsSmall utilities that fit Git work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Git guides
All Git guidesGit config: Aliases, rerere, and Credential Helpers
Five config scopes decide one value at a time. Aliases are user-level shorthand, rerere records conflict resolutions, and credential helpers choose where your secret lives.
Git bisect: Binary Search, Automated Scripts, and Bug Hunting
Mark one bad and one good commit and Git halves the range each step. bisect run automates it through exit codes, and monotonicity is the assumption that must hold.
Git ignore: Patterns, Negation, and Untracking Cached Files
Patterns are relative and last match wins, but a negation cannot revive a file inside an excluded directory. Ignore rules never touch tracked files: rm --cached first.
Git worktree: Multiple Checked-Out Branches in One Repository
A linked worktree has its own HEAD, index, and files while sharing objects and refs. One branch per worktree, prune for deleted directories, and submodules that stay empty.
More in Git
All Git guidesThe guides filed next to this one in Git, in library order.