Git hooks

Also known as: pre-commit hook

On this page 7

Git hooks are executable scripts that Git runs automatically at defined points in its workflow, such as before a commit is recorded, after a merge or when a push reaches a server. Among development tools in programming, they are the built-in mechanism for enforcing local rules and triggering automation without changing Git itself.

A hook is selected purely by its file name, for example pre-commit or pre-push, and lives by default in the .git/hooks directory of a repository. If a pre-* hook exits with a non-zero status, Git aborts the operation, which is how a pre-commit hook can stop code that fails a linter or a test from being committed.

How Git discovers and runs hooks

When an operation reaches a hook point, Git looks for an executable file with the exact hook name in the hooks directory and runs it. Every new repository contains sample files ending in .sample; they stay inactive until renamed and made executable. Hooks can be written in any language with a valid interpreter line, including shell, Python or Node.js.

Git passes context through command-line arguments and standard input. The commit-msg hook receives the path of the file holding the proposed message, while pre-push receives the remote name and URL as arguments and the list of refs being pushed on standard input. The exit status is the verdict: zero lets the operation continue, anything else stops it for blocking hooks.

Since Git 2.9, the core.hooksPath setting can point to any directory, which lets a team store hooks in a tracked folder such as .githooks instead of the untracked .git/hooks.

Hooks run with the repository root as the working directory for most client-side operations, and Git sets environment variables such as GIT_DIR and GIT_INDEX_FILE that a script can use. A common mistake is a hook that calls Git commands while those variables point elsewhere, for example inside a linked worktree, which leads to confusing results. Robust hooks therefore resolve paths explicitly with git rev-parse before acting.

Client-side and server-side hook types

Hooks fall into two groups: client-side hooks run in a developer’s local clone, and server-side hooks run on the repository that receives pushes. Only server-side hooks can enforce policy reliably, because a developer can skip or delete local hooks.

The following table lists the most commonly used hooks and when Git invokes them.

HookSideRuns whenCan block
pre-commitClientBefore the commit message is requestedYes
prepare-commit-msgClientBefore the message editor opensYes
commit-msgClientAfter the message is writtenYes
post-commitClientAfter the commit is createdNo
pre-pushClientBefore objects are sent to a remoteYes
post-checkoutClientAfter a checkout or switchNo
pre-receiveServerOnce per push, before refs updateYes
updateServerOnce per ref being updatedYes
post-receiveServerAfter all refs are updatedNo
Commonly used Git hooks

Hosted platforms such as GitHub and GitLab.com generally do not allow custom server-side hooks on shared infrastructure. They offer equivalent controls through branch protection rules, required status checks and webhooks, while self-managed servers can install pre-receive hooks directly.

Typical tasks automated with hooks

Hooks are most valuable for fast, deterministic checks that catch problems before they leave a developer’s machine. The decisive design rule is speed: a pre-commit hook that takes more than a few seconds encourages developers to bypass it habitually.

TaskSuitable hookReason
Run a linter or code formatterpre-commitChecks only staged files, quickly
Enforce a commit message formatcommit-msgHas direct access to the message
Insert a ticket number from the branchprepare-commit-msgEdits the message before the editor
Run the unit test suitepre-pushSlower checks run less often
Scan for leaked secretspre-commit or pre-receiveStops credentials before they spread
Reinstall dependencies after a pullpost-mergeKeeps the environment in sync
Trigger a deploymentpost-receiveRuns once the push is accepted
Tasks matched to suitable hooks

A well-designed pre-commit hook inspects only the staged changes, not the whole working tree, so that unstaged edits do not cause false failures or false passes.

Sharing hooks across a team

The .git directory is not version controlled, so hooks placed there are not shared when a repository is cloned. Teams therefore rely on a hook manager or on a committed hooks directory plus core.hooksPath.

OptionHow it worksBest suited to
core.hooksPathPoints Git at a tracked directorySmall teams, no extra dependency
pre-commit frameworkYAML config, isolated tool environmentsPolyglot repositories
HuskyInstalls hooks through npm scriptsJavaScript projects
LefthookSingle binary, parallel commandsLarge monorepos
Options for distributing hooks

Whichever option is chosen, installation usually still requires one setup step per clone, often automated through a package install script, because Git deliberately does not run code from a freshly cloned repository.

Limitations and security considerations

Client-side hooks are advisory, not enforcement. Any developer can skip pre-commit and commit-msg hooks with git commit --no-verify, and pre-push with git push --no-verify. Rules that must always hold belong in server-side hooks or CI pipelines as well.

  • Arbitrary code execution: hooks run with the user’s permissions, so hooks from untrusted sources must be reviewed before installation.
  • Environment drift: a hook that depends on a locally installed tool fails on machines with a different version.
  • Graphical clients: some IDEs run hooks with a reduced PATH, causing tools to appear missing.
  • Slow hooks: long checks block every commit and push developers toward bypassing them.
  • Rebases and merges: hooks may run many times during history rewriting, multiplying their cost.

A plain-language summary

Git hooks are small automatic helpers that Git calls at certain moments, for example right before saving a change or before sending work to a shared server. Each helper can check the work and either let it through or stop it.

They resemble a spell checker that runs before an email is sent. Local hooks are a convenient safety net, but a determined person can switch them off, so important rules are also checked on the server.

An example from practice

A team of twelve backend developers working on a Python service keeps finding formatting noise and occasional API tokens in code review. They add a configuration for the pre-commit framework that runs a formatter, a linter and a secret scanner on staged files only, and a pre-push hook that runs the fast unit tests.

The pre-commit checks finish in under three seconds for a typical change, so nobody bothers to skip them. Within a month, review comments about style nearly disappear, and the scanner blocks two commits containing cloud credentials before they ever leave a laptop. Because hooks can be bypassed, the same checks also run as required CI status checks, which catch the rare commit made with --no-verify.