How to Create Custom Git Hook: Simple Guide
To create a custom
git hook, write an executable script inside the .git/hooks directory of your repository with the hook's name (like pre-commit). Make sure the script has execute permissions, and Git will run it automatically during the corresponding event.Syntax
Git hooks are scripts placed in the .git/hooks folder of your repository. Each hook is a file named after the Git event it triggers on, such as pre-commit or post-commit. The script must be executable and can be written in any scripting language like Bash or Python.
Basic syntax to create a hook:
.git/hooks/<hook-name>: The hook script file.- Make the script executable with
chmod +x. - The script runs automatically when the Git event occurs.
bash
# Example: Creating a pre-commit hook # 1. Create a file named 'pre-commit' in .git/hooks/ # 2. Add your script commands # 3. Make it executable chmod +x .git/hooks/pre-commit
Example
This example shows a simple pre-commit hook that prevents commits if any file contains the word 'WIP' (work in progress). It helps avoid committing unfinished work.
sh
#!/bin/sh # pre-commit hook to block commits with 'WIP' in any staged file git diff --cached --name-only | while read file; do if git show :"$file" | grep -q 'WIP'; then echo "Error: Commit blocked because '$file' contains 'WIP'." exit 1 fi done exit 0
Output
Error: Commit blocked because 'example.txt' contains 'WIP'.
Common Pitfalls
Common mistakes when creating Git hooks include:
- Not making the hook script executable, so Git ignores it.
- Using the wrong filename or placing the script outside
.git/hooks. - Writing scripts that do not exit with
0on success, causing Git to block operations unexpectedly. - Assuming hooks are shared automatically; hooks are local and not pushed to remote repositories.
bash
# Wrong: script without execute permission # .git/hooks/pre-commit (no chmod +x) # Right: add execute permission chmod +x .git/hooks/pre-commit
Quick Reference
| Hook Name | When It Runs | Purpose |
|---|---|---|
| pre-commit | Before commit is finalized | Check code or run tests before commit |
| commit-msg | After commit message is entered | Validate commit message format |
| post-commit | After commit is done | Notify or trigger other actions |
| pre-push | Before pushing to remote | Run tests or checks before push |
Key Takeaways
Place your hook script in the .git/hooks directory with the exact hook name.
Make the hook script executable using chmod +x to enable it.
Hooks run automatically during Git events like commit or push.
Hooks are local and not shared via Git; share them manually if needed.
Exit with 0 to allow Git operation, non-zero to block it.