Skip to content
BENIBIX Learn

Git Hook

Development🔀 Version ControlGit Basics

Also known as Git Hooks, Pre-Commit Hook, pre-commit, commit-msg Hook

A script Git runs on its own, like a check just before each commit.

Think of it like

Think of it like a guard at a door. Before you go through, the guard checks your ticket.

Example

Emma's pre-commit hook runs the tests. When a test fails, her commit is stopped until she fixes it.

Why it matters

It catches mistakes on your own machine, before anyone else sees them.

Definition

A Git hook is a script Git runs by itself at a set moment. The pre-commit hook runs just before a commit is made. If it ends with an error, Git stops and the commit is not made. Other hooks run when a message is written or before a push. Hooks live in the .git/hooks folder, so each person's copy has its own.

Example code

bash
#!/bin/sh
# .git/hooks/pre-commit
npm test || exit 1
If the tests fail, the hook exits with 1 and the commit is stopped.
The pre-commit hook runs the tests. A fail stops the commit.

Common mistake

Thinking a hook protects the whole team. Hooks are not shared by a clone, and git commit --no-verify skips them.

Key takeaways

  1. 1
    Runs on its own. Git calls it at a set moment.
  2. 2
    Can say no. An error stops the commit.
  3. 3
    Local only. Each copy has its own hooks.

Compare

Learn it properly