A Real Hook, Checking Staged Content
#!/bin/sh
for f in $(git diff --cached --name-only); do
if [ -f "$f" ] && grep -q "TODO: remove before commit" "$f"; then
echo "ERROR: $f contains 'TODO: remove before commit'"
exit 1
fi
case "$f" in
*.env|.env) echo "ERROR: refusing to commit a .env file: $f"; exit 1 ;;
esac
done
exit 0
git diff --cached --name-only lists exactly the real files about to be committed — the hook inspects each one directly.
Two Real, Separate Rejections
git commit -m "RECIPE-302: Add debug notes"
# ERROR: debug-notes.md contains 'TODO: remove before commit'
git add -f .env
git commit -m "RECIPE-303: Add local env file"
# ERROR: refusing to commit a .env file: .env
Even a real, deliberate -f past .gitignore does not help — the hook checks staged content directly, independent of .gitignore entirely.
A pre-commit hook runs even earlier than commit-msg — before a message is written at all — and has direct access to exactly what is genuinely staged via git diff --cached. This lab writes one real hook covering two real, common mistakes: a staged file still containing a literal "TODO: remove before commit" marker, and a real .env file someone force-added despite it already being gitignored.
Both get a real, direct rejection — the exact same non-zero-exit mechanism as commit-msg, just checking the real staged tree instead of a message.
pre-commit hook
A real, local script git runs before a commit message is even written, with direct access to the real staged content via git diff --cached. Confirmed directly in this lab: it rejected both a marker string inside a file and a filename pattern, independent of .gitignore.
git diff --cached --name-only
Lists exactly the real files currently staged for the next commit. Confirmed directly in this lab: this is exactly what the hook iterated over to inspect each staged file.
Takeaways
- A pre-commit hook runs before any commit message is written and can inspect real staged content directly
- git diff --cached --name-only lists exactly the files about to be committed
- A hook-based check is independent of .gitignore — it still catches a file force-added with -f
- Real teams often layer both commit-msg and pre-commit hooks, each catching a different category of mistake