How to Use Git Pre-commit Hook: Simple Guide
A
pre-commit hook is a script that Git runs automatically before a commit is saved. To use it, create an executable script named pre-commit inside the .git/hooks/ folder of your repository. This script can check code style, run tests, or block commits if conditions fail.Syntax
The pre-commit hook is a script placed in the .git/hooks/pre-commit file. It must be executable and can be written in any scripting language like Bash or Python.
When you run git commit, Git executes this script before completing the commit. If the script exits with a non-zero status, the commit is stopped.
.git/hooks/pre-commit: The hook script file- Executable permission: The script must be executable (
chmod +x) - Exit status:
0means success, any other value blocks the commit
sh
#!/bin/sh # This is the pre-commit hook script # Commands to run before commit # Exit 0 to allow commit exit 0
Example
This example shows a simple pre-commit hook that checks if any Python files have syntax errors before allowing the commit.
sh
#!/bin/sh # Check Python syntax for all staged .py files files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.py$') if [ -z "$files" ]; then exit 0 fi for file in $files; do python3 -m py_compile "$file" if [ $? -ne 0 ]; then echo "Syntax error in $file. Commit aborted." exit 1 fi done exit 0
Output
Syntax error in script.py. Commit aborted.
Common Pitfalls
- Not making the
pre-commitscript executable will prevent it from running. - Using commands that require unstaged changes can cause false negatives; always check staged files.
- Forgetting to exit with
0on success or non-zero on failure will cause unexpected commit behavior. - Long-running scripts can slow down commits and frustrate users.
sh
# Wrong: script not executable # File created but no chmod +x # Right: make script executable chmod +x .git/hooks/pre-commit
Quick Reference
| Step | Description |
|---|---|
| Create script | Add your script to .git/hooks/pre-commit |
| Make executable | Run chmod +x .git/hooks/pre-commit |
| Test script | Run git commit to trigger the hook |
| Exit codes | Use 0 to allow commit, non-zero to block |
| Check staged files | Use git diff --cached to inspect files |
Key Takeaways
Place your pre-commit script in .git/hooks/pre-commit and make it executable.
Use exit code 0 to allow commits and non-zero to block them.
Check only staged files to avoid false errors.
Keep pre-commit scripts fast to avoid slowing down commits.
Test your hook by running git commit and observing behavior.