1. Home
  2. Blog
  3. DevOps

DevOps

Git Hooks Explained: Pre-commit and Commit-msg Scripts That Work

Git hooks are scripts Git runs automatically at moments such as commit and push. Use them to block debug code, enforce commit message rules and add ticket IDs. See tested hook scripts, how to share them with core.hooksPath, how –no-verify bypasses them, and when to use a hook manager.

9 min read
Git hooks: pre-commit and commit-msg examples

Key takeaways

  • Git hooks are executable scripts in a hooks folder. A non-zero exit code from a “pre” hook stops the action.
  • Hooks in .git/hooks are not shared. Commit them to a folder such as .githooks and run git config core.hooksPath .githooks.
  • Our pre-commit hook blocked a commit containing breakpoint(), and our commit-msg hook rejected “added total”.
  • Hooks run on the developer’s machine and --no-verify skips them, so repeat important checks in CI.

Code review keeps finding the same small problems: a forgotten debug breakpoint, a merge conflict marker, a commit message that says “fix” and nothing else. Each one wastes a reviewer’s time. Git hooks catch them on the developer’s machine before the commit even exists, in a fraction of a second.

We built and tested every hook below in a throwaway repository with Git 2.56, using Git Bash on Windows with a demo identity. The scripts are plain POSIX shell, so they also run on Linux and macOS.

What are git hooks?

A hook is a script that Git runs automatically when a certain event happens, such as just before a commit is recorded. Git passes it information through arguments and standard input. For “pre” hooks, the exit code decides what happens next: 0 lets the action continue, anything else aborts it. “Post” hooks run after the event and cannot stop it, so they suit notifications.

Where hooks live

Every new repository gets sample hooks. Our git init created 14 of them in .git/hooks, including pre-commit.sample, commit-msg.sample, pre-push.sample and prepare-commit-msg.sample. They do nothing until you remove the .sample suffix and make the file executable. Git ignores hooks without the executable bit.

The catch: .git is never committed, so hooks you put there exist only on your machine. Teammates do not get them, and neither does a fresh clone.

The most useful client-side hooks

Hook Runs Can block? Typical use
pre-commit Before the commit message is asked for Yes Lint, format check, block debug code and secrets
prepare-commit-msg Before the editor opens Yes Pre-fill the message, add a ticket ID
commit-msg After the message is written Yes Enforce a message format
post-commit After the commit No Notifications
pre-push Before data is sent to a remote Yes Run fast tests, block pushes to main
post-checkout / post-merge After switching branches or merging No Reinstall dependencies when lock files change

Sharing hooks with core.hooksPath

Since Git 2.9, the core.hooksPath setting tells Git to look for hooks in any folder. Put your hooks in a committed folder and point Git at it:

mkdir .githooks
# ...add hook scripts...
chmod +x .githooks/*
git config core.hooksPath .githooks
git config --get core.hooksPath
# .githooks

The hooks are now versioned with the code and reviewed like any other change. Each developer still runs the git config line once after cloning, because Git will never enable hooks automatically for security reasons. A setup script or a make setup style command is a good place for it.

A pre-commit hook: block debug code and conflict markers

#!/bin/sh
# .githooks/pre-commit
# Block commits that contain leftover debug code or merge markers.
status=0
for f in $(git diff --cached --name-only --diff-filter=ACM -- '*.py'); do
  if git diff --cached -U0 -- "$f" | grep -nE '^\+.*(breakpoint\(\)|import pdb)'; then
    echo "pre-commit: debug code in $f" >&2
    status=1
  fi
done
if git diff --cached -U0 | grep -qE '^\+(<<<<<<<|>>>>>>>)'; then
  echo "pre-commit: merge conflict markers found" >&2
  status=1
fi
exit $status

Key details:

  • git diff --cached checks the staged changes, which is what will be committed, not the whole working folder.
  • --diff-filter=ACM includes added, copied and modified files and skips deleted ones.
  • Matching lines that start with + means only newly added lines are checked, so old code does not block new commits.
  • Messages go to standard error, and the script exits with 1 when anything is found.

A commit-msg hook: enforce Conventional Commits

#!/bin/sh
# .githooks/commit-msg
# Enforce Conventional Commits: type(scope): subject
msg_file="$1"
first_line=$(head -n1 "$msg_file")
pattern='^(feat|fix|docs|test|refactor|chore)(\([a-z0-9-]+\))?: .{1,60}$'
if ! echo "$first_line" | grep -qE "$pattern"; then
  echo "commit-msg: '$first_line' does not match type(scope): subject" >&2
  exit 1
fi

Git passes the path of a temporary file holding the message as the first argument. The hook reads the first line and checks it against the pattern. Consistent messages make history readable and let tools generate changelogs and semantic version bumps automatically.

Watching the hooks run

We staged a Python file containing breakpoint() and tried to commit with a valid message:

git commit -m "feat(cart): add total"
8:+    breakpoint()
pre-commit: debug code in cart.py
exit=1

Blocked, with the offending line shown. We removed the breakpoint and tried a vague message:

git commit -m "added total"
commit-msg: 'added total' does not match type(scope): subject
exit=1

Blocked again, this time by the second hook. With both problems fixed, the commit went through:

git commit -m "feat(cart): add total helper"
exit=0

prepare-commit-msg: add the ticket ID automatically

Many teams put the ticket ID in every message. This hook reads it from a branch name such as feature/SQ-42-login:

#!/bin/sh
# .githooks/prepare-commit-msg
branch=$(git symbolic-ref --short HEAD 2>/dev/null)
ticket=$(echo "$branch" | grep -oE '[A-Z]+-[0-9]+')
if [ -n "$ticket" ] && [ "$2" = "message" ]; then
  sed -i "1s/^/[$ticket] /" "$1"
fi

The second argument tells the hook where the message came from; message means it was given with -m. On our first try, the two hooks clashed:

commit-msg: '[SQ-42] feat(auth): add login stub' does not match type(scope): subject

prepare-commit-msg runs before commit-msg, so the validator saw the prefixed message and rejected it. We allowed an optional ticket prefix in the pattern:

pattern='^(\[[A-Z]+-[0-9]+\] )?(feat|fix|docs|test|refactor|chore)(\([a-z0-9-]+\))?: .{1,60}$'

Then the commit succeeded with the message [SQ-42] feat(auth): add login stub. We also checked the pattern on its own: it accepted feat: x and rejected added total, [sq-1] feat: x and Feat: y. Test hooks together, not just one at a time.

Bypassing hooks with –no-verify

git commit --no-verify -m "wip"
exit=0

We staged a file with a breakpoint and committed with --no-verify: both pre-commit and commit-msg were skipped and the commit was created, bad message and all. That escape hatch is useful in emergencies, but it means hooks are a convenience, not a guarantee. Anyone can skip them, and new clones do not have them until setup runs. Every rule that truly matters must also run in CI, as described in our GitHub Actions CI/CD guide.

Hook managers: pre-commit and Husky

Hand-written shell hooks are fine for a few checks. As rules grow, a manager helps:

  • pre-commit (the Python framework): a .pre-commit-config.yaml file lists hooks from a large catalogue, such as formatters, linters and secret scanners, each pinned to a version. pre-commit install wires them up, and pre-commit run --all-files runs them on demand or in CI.
  • Husky: popular in JavaScript projects. It stores hooks in a committed .husky/ folder and sets core.hooksPath for you during npm install.
  • lint-staged: often paired with Husky to run tools only on staged files, which keeps hooks fast.

Managers solve the setup and versioning problems, and they run the same checks on every machine.

Server-side hooks

Git also has server-side hooks such as pre-receive and update, which run on the remote and can reject pushes. They cannot be bypassed by developers. Hosted platforms such as GitHub and GitLab usually do not let you install them; instead, they offer branch protection rules and required status checks, which achieve the same goal.

Notes for Windows users

  • Git for Windows runs hooks through its bundled shell, so #!/bin/sh scripts work, as in our tests.
  • Save hook files with LF line endings. A CRLF in the first line breaks the shebang.
  • Set the executable bit in the repository with git update-index --chmod=+x .githooks/pre-commit so teammates on Linux and macOS get runnable files.

Tip: keep hooks fast. A pre-commit hook that takes 30 seconds teaches people to use --no-verify. Move slow test suites to pre-push or CI.

Best practices

  1. Commit hooks to the repository and set core.hooksPath in your setup script.
  2. Check only staged changes, and only newly added lines where possible.
  3. Print clear messages that say what failed and how to fix it.
  4. Keep pre-commit under a few seconds.
  5. Duplicate every important rule in CI, because hooks can be skipped.
  6. Scan for secrets such as API keys and private keys before they ever reach history.

Final thoughts

Git hooks are a cheap way to stop small mistakes at the source. A short pre-commit script blocks debug code and conflict markers, a commit-msg script keeps history clean, and prepare-commit-msg saves typing. Share them with core.hooksPath or a hook manager, keep them fast, test them together, and back them up in CI, because a hook only helps when it runs.

FAQ

What are git hooks used for?

They run scripts automatically at Git events such as commit or push, to lint code, block debug statements, enforce message formats or run quick tests.

How do I share git hooks with my team?

Commit the hook scripts to a folder such as .githooks and have each developer run git config core.hooksPath .githooks, or use a manager such as pre-commit or Husky.

How do I skip a git hook?

Add the no-verify option to git commit or git push. Because anyone can do this, important checks should also run in CI.

Why is my git hook not running?

The file may lack the executable bit, still have the sample suffix, use Windows line endings, or core.hooksPath may point to a different folder.

What is the difference between pre-commit and commit-msg hooks?

pre-commit runs before the message exists and checks the staged code. commit-msg runs after the message is written and checks the message text.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
Software Development

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →