← Back to Git Course | Chapter 6: Advanced Commands | Lesson 2 of 7

Git Hooks

Locating Git Hooks Directory

Git hooks are shell scripts Git runs automatically at specific points in its workflow — before a commit, after a merge, before a push, and so on. They live in the .git/hooks/ directory of a repository as plain executable files (e.g. pre-commit), and Git ignores any file there that isn't named exactly right or isn't executable.

Example: Locating Git Hooks Directory

bash
ls .git/hooks/

Setting Up a Pre-commit Hook

A pre-commit hook runs right before Git opens the commit message editor, and if the script exits with a non-zero status, the commit is aborted — making it the natural place to enforce a linter, run a quick test suite, or block commits containing debug statements.

Example: Setting Up a Pre-commit Hook

bash
echo '#!/bin/sh\nnpm run lint' > .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit

Bypassing Active Hooks

git commit --no-verify (or -n) skips both the pre-commit and commit-msg hooks for that one commit, letting you push through in a genuine emergency — but relying on it routinely defeats the point of having the hook at all.

Example: Bypassing Active Hooks

bash
git commit --no-verify -m "Emergency fix"

Configuring Global Hooks

Because .git/hooks/ isn't tracked by Git and doesn't get cloned with the repo, hooks you write are local-only by default. Setting core.hooksPath to a shared, version-controlled directory (via git config core.hooksPath .githooks) is how teams distribute the same hooks to everyone.

Example: Configuring Global Hooks

bash
git config core.hooksPath .githooks

Creating Post-merge Hooks

A post-merge hook fires right after git merge or git pull completes, which makes it a good place to automatically reinstall dependencies or clear a stale build cache if the merge changed a lockfile — catching a class of "works on my machine" bugs caused by an out-of-date environment.

Example: Creating Post-merge Hooks

bash
echo '#!/bin/sh\nnpm install' > .git/hooks/post-merge
chmod +x .git/hooks/post-merge
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.