Git Hooks - Automate on Events
Git Hooks
Hooks are scripts Git runs automatically on events - enforce standards before bad code enters history.
| Hook | Fires | Common use |
|---|---|---|
pre-commit | Before a commit is created | Lint, format, run fast tests, block secrets |
commit-msg | After the message is written | Enforce message format (e.g. Conventional Commits) |
pre-push | Before pushing | Run the test suite |
Hooks live in .git/hooks/ as executable scripts:
$ cat > .git/hooks/pre-commit <<'EOF'
#!/bin/bash
if git diff --cached | grep -q 'API_KEY='; then
echo 'Blocked: do not commit secrets!'; exit 1
fi
EOF
$ chmod +x .git/hooks/pre-commit
Warning:.git/hooks/is not committed or shared with the team. To share hooks, use a tool like Husky (JS) or pre-commit (Python), or setcore.hooksPathto a tracked directory.
Tip: A pre-commit hook that blocks secrets and runs a linter catches problems on your machine - before they ever reach CI or review.