What are Git hooks and how to create custom ones
· Category: Git
Short answer
Git hooks are scripts that run automatically when specific Git events occur. Store them in .git/hooks/ with names like pre-commit, pre-push, or post-merge. Make them executable with chmod +x. For branching strategies that complement hooks, see how to create a new Git branch.
Common hooks
- pre-commit: Runs before each commit. Use it for linting, formatting, or running tests.
- pre-push: Runs before pushing. Use it to prevent pushing failing tests.
- commit-msg: Validates commit message format.
- post-merge: Runs after a merge completes. Use it for dependency installation.
Example pre-commit hook
#!/bin/sh
npm run lint
if [ $? -ne 0 ]; then
echo "Lint failed. Fix errors before committing."
exit 1
fi
Tips
- Use a tool like Husky or pre-commit to share hooks via the repository
- Hooks are not version-controlled by default — use a framework to manage them
- See how to set up a .gitignore file for keeping your repository clean