Where Are Git Hooks Stored: Location and Usage Explained
Git hooks are stored in the
.git/hooks directory inside your local git repository. Each hook is a script file that runs automatically on specific git events like commits or pushes.Syntax
The git hooks are stored as executable script files inside the .git/hooks folder of your repository. Each hook has a specific name corresponding to a git event, such as pre-commit or post-merge.
To use a hook, you create or modify the script file with the exact hook name inside .git/hooks. The script must be executable.
bash
ls .git/hooks # Lists all available hook scripts # Example hook file path: .git/hooks/pre-commit
Output
applypatch-msg.sample
commit-msg.sample
post-commit.sample
pre-commit.sample
pre-push.sample
pre-rebase.sample
prepare-commit-msg.sample
update.sample
Example
This example shows how to create a simple pre-commit hook that prevents commits if the commit message is empty.
bash
# Navigate to the hooks directory cd .git/hooks # Create a pre-commit hook script cat << 'EOF' > pre-commit #!/bin/sh # Check if commit message is empty if [ -z "$(git log -1 --pretty=%B)" ]; then echo "Commit message cannot be empty." exit 1 fi EOF # Make the script executable chmod +x pre-commit
Common Pitfalls
- Forgetting to make the hook script executable with
chmod +xcauses the hook not to run. - Modifying the wrong directory; hooks must be inside the
.git/hooksfolder of the local repository. - Using incorrect script syntax or unsupported languages can cause hooks to fail silently.
- Relying on hooks for critical checks without informing team members can cause confusion since hooks are local and not shared by default.
bash
# Wrong: Hook script without executable permission ls -l .git/hooks/pre-commit -rw-r--r-- 1 user user 123 Apr 1 12:00 pre-commit # Right: Make it executable chmod +x .git/hooks/pre-commit ls -l .git/hooks/pre-commit -rwxr-xr-x 1 user user 123 Apr 1 12:00 pre-commit
Output
-rw-r--r-- 1 user user 123 Apr 1 12:00 pre-commit
-rwxr-xr-x 1 user user 123 Apr 1 12:00 pre-commit
Quick Reference
Summary tips for git hooks location and usage:
- Hooks live in
.git/hooksinside your repository. - Each hook is a script named after the git event it hooks into.
- Make scripts executable with
chmod +x. - Hooks run locally and are not shared unless committed separately.
Key Takeaways
Git hooks are stored in the .git/hooks directory inside your local repository.
Each hook is a script file named after a git event and must be executable to run.
Hooks run automatically on git events like commit or push but are local to your machine.
Always make hook scripts executable with chmod +x to ensure they work.
Hooks are not shared by default; share them manually if needed.