Jane Doe
Pro Plan
Git hooks are powerful tools that let you automate tasks during the Git workflow. One of the most commonly used hooks is the pre-commit hook. This script runs before a commit is finalized, making it ideal for tasks like linting code, running tests, or formatting files automatically.
In this post, you’ll learn what Git pre-commit hooks are, how to use them, and see examples with plain shell scripts and modern tools like Husky.
A pre-commit hook is a script that runs right before a git commit is executed. If the script exits with a non-zero status, the commit will be aborted. This makes it a useful safeguard to prevent bad or broken code from being committed.
Git looks for hooks in the .git/hooks directory inside your repository.
Git initializes example hooks when you create a repository. To enable the pre-commit hook:
.git/hooks/pre-commit.sample to pre-commitchmod +x .git/hooks/pre-commitHere's a simple pre-commit script that runs ESLint before allowing the commit:
#!/bin/sh echo "Running ESLint..."npx eslint . || { echo "ESLint failed. Commit aborted." exit 1}If ESLint fails, the commit will not proceed.
Native Git hooks aren't shared with the repo. To version-control your hooks and ensure everyone runs them, use Husky.
npm install husky --save-devnpx husky installAdd this to your package.json scripts:
"scripts": { "prepare": "husky install"}npx husky add .husky/pre-commit "npm run lint"This creates a .husky/pre-commit file with:
#!/bin/sh. "$(dirname "$0")/_/husky.sh" npm run lintNow every time you run git commit, Husky will trigger the hook and run your lint script.
eslint, stylelint)prettiertsc)pre-push or prettier --write script and stage them manually.Git pre-commit hooks are a great way to improve code quality and enforce consistency before code is committed. Whether you’re working solo or on a team, adding pre-commit hooks can help catch mistakes early and reduce tech debt.
By using tools like Husky, you can easily manage these hooks in your repo and make sure everyone on your team benefits from them.
Start small — add a linter or formatter hook, and build from there!
Happy committing! 🚀