Day 24beginnerFeb 24, 2026

Catch Mistakes Before They're Committed with Git Hooks

Pre-commit hooks automatically catch bugs, lint errors, and formatting issues before they enter your codebase.

gitautomationcode-quality
Share:

What

Git hooks are scripts that run automatically at certain points in the Git workflow. Pre-commit hooks run before a commit is created, giving you a chance to validate code, run linters, check formatting, or run tests. If the hook exits with a non-zero status, the commit is aborted.

Why It Matters

Catching issues at commit time is far cheaper than catching them in code review or production. Pre-commit hooks enforce code quality standards automatically, so developers don't have to remember to run linters manually. They keep your commit history clean and your CI pipeline green.

Example

# Option 1: Manual hook β€” create .git/hooks/pre-commit
#!/bin/sh
npm run lint
if [ $? -ne 0 ]; then
  echo "Lint failed. Fix errors before committing."
  exit 1
fi

# Make it executable
chmod +x .git/hooks/pre-commit

# Option 2: Using husky + lint-staged (recommended for teams)
npx husky-init && npm install
npx husky set .husky/pre-commit "npx lint-staged"

# In package.json, add:
# "lint-staged": {
#   "*.{js,ts}": ["eslint --fix", "prettier --write"]
# }
bash

Common Mistake

Not making the hook file executable with chmod +x. The hook file exists but Git silently ignores it because it doesn't have execute permissions.

Quick Fix

Always run chmod +x .git/hooks/pre-commit after creating a hook. For team projects, use husky to manage hooks via package.json so they're version-controlled and automatically installed.

Key Takeaways

  • 1Pre-commit hooks run automatically before every commit
  • 2Non-zero exit code aborts the commit
  • 3chmod +x is required for hook scripts to execute
  • 4Use husky + lint-staged for team-friendly hook management
  • 5Hooks catch lint errors, formatting issues, and test failures early

Was this tip helpful?

Help us improve the DevOpsPath daily collection

Share: