Git Hooks: Automate Tasks on Git Events

Learn how to use git hooks to automate linting, testing, and formatting on commit, push, and other git events. Local and server-side.

chmod +x .git/hooks/pre-commit

Detailed Explanation

What Are Git Hooks?

Git hooks are scripts that run automatically when specific Git events occur — such as committing, pushing, or merging. They live in the .git/hooks/ directory and can be written in any scripting language (bash, Python, Node.js, etc.).

Common Client-Side Hooks

Hook Trigger Common Use
pre-commit Before commit is created Lint, format, type-check
commit-msg After message is written Validate commit message format
pre-push Before push to remote Run tests
post-merge After a merge completes Install dependencies
post-checkout After branch switch Notify, rebuild

Creating a Pre-Commit Hook

# .git/hooks/pre-commit
#!/bin/sh
npm run lint
if [ $? -ne 0 ]; then
  echo "Linting failed. Commit aborted."
  exit 1
fi
chmod +x .git/hooks/pre-commit

Sharing Hooks with the Team

Hooks in .git/hooks/ are not committed to the repository. To share them:

  1. Store hooks in a committed directory (e.g., .githooks/).
  2. Configure Git to use that directory:
git config core.hooksPath .githooks

Popular Hook Frameworks

  • Husky (Node.js) — the most popular for JavaScript projects.
  • pre-commit (Python) — language-agnostic with a large plugin ecosystem.
  • lefthook (Go) — fast, parallel hook execution.

Server-Side Hooks

Hooks can also run on the server (e.g., GitLab, self-hosted Git):

Hook Trigger
pre-receive Before accepting a push
post-receive After accepting a push
update Per-branch, before updating ref

Tips

Keep hooks fast — slow pre-commit hooks frustrate developers and get bypassed. Run heavy tasks (full test suites) in pre-push instead. Git hooks are the first line of defense for code quality.

Use Case

A team sets up a pre-commit hook with Husky to automatically run ESLint and Prettier on staged files, ensuring every commit meets the project's code style standards.

Try It — Git Command Builder

Open full tool