How to set up a pre-commit hook in Git
· Category: Git
Short answer
Create an executable script in .git/hooks/pre-commit to run checks before each commit.
Steps
- Create the hook file:
touch .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
- Add a simple check:
#!/bin/bash
echo "Running pre-commit checks..."
pytest
if [ $? -ne 0 ]; then
echo "Tests failed. Commit aborted."
exit 1
fi
- Use the pre-commit framework for easier management:
pip install pre-commit
pre-commit install
Tips
- Hooks are local; share them via a framework or symlink script.
- Keep hooks fast so they do not slow down the commit flow.
pre-pushhooks are useful for longer test suites.
Common issues
- Hooks not running: ensure the file is executable and has no extension on Unix.
- Bypass hooks with
git commit --no-verifywhen necessary.