How to Share Git Hooks with Your Team Easily
To share
git hooks with your team, store the hooks scripts in a directory inside your repository (e.g., hooks/) and use a setup script or Git configuration to link them to the .git/hooks folder. This ensures everyone uses the same hooks automatically when they clone the repo.Syntax
Git hooks are scripts placed in the .git/hooks directory that run on specific Git events. To share hooks, you keep them in a version-controlled folder like hooks/ and create symbolic links or copy them to .git/hooks.
Typical commands:
ln -s ../../hooks/pre-commit .git/hooks/pre-commit- creates a symbolic link for the pre-commit hookchmod +x hooks/pre-commit- makes the hook script executable
bash
ln -s ../../hooks/pre-commit .git/hooks/pre-commit chmod +x hooks/pre-commit
Example
This example shows how to share a pre-commit hook that checks for trailing whitespace before commits.
Store the hook script in hooks/pre-commit and run a setup script to link it.
bash
# hooks/pre-commit #!/bin/sh # Check for trailing whitespace if git diff --cached --check | grep -q 'trailing whitespace'; then echo 'Error: Trailing whitespace found. Please fix before commit.' exit 1 fi # setup-hooks.sh #!/bin/sh mkdir -p .git/hooks ln -sf ../../hooks/pre-commit .git/hooks/pre-commit chmod +x hooks/pre-commit echo 'Git hooks installed.'
Output
Git hooks installed.
Common Pitfalls
Common mistakes when sharing Git hooks include:
- Not making hook scripts executable with
chmod +x. - Placing hooks only in
.git/hookswhich is not version controlled, so teammates don’t get them. - Forgetting to run the setup script after cloning the repo.
- Using absolute paths in hooks that don’t work on other machines.
Always use relative paths and automate setup.
bash
# Wrong: placing hooks only in .git/hooks (not shared) # Right: store hooks in repo and link them # Wrong: forgetting chmod +x # Right: chmod +x hooks/pre-commit
Quick Reference
| Step | Command / Action | Purpose |
|---|---|---|
| 1 | Create hooks directory in repo (e.g., hooks/) | Store hook scripts under version control |
| 2 | Write hook scripts (e.g., pre-commit) | Define checks or actions on Git events |
| 3 | Make scripts executable | chmod +x hooks/pre-commit |
| 4 | Create setup script to link hooks | ln -sf ../../hooks/pre-commit .git/hooks/pre-commit |
| 5 | Run setup script after cloning | Installs hooks for each team member |
Key Takeaways
Store Git hooks inside the repository to share them with your team.
Use a setup script to link or copy hooks into the .git/hooks folder automatically.
Make sure hook scripts are executable with chmod +x.
Avoid absolute paths in hooks to keep them portable across machines.
Remind teammates to run the setup script after cloning the repo.