Hands-On: A Pre-Commit Hook
Hands-On: Create a Pre-Commit Hook
Install a pre-commit that runs git diff --cached --check on desk-api.
cd ~/desk/desk-api
cat > .git/hooks/pre-commit <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
echo "pre-commit: git diff --cached --check" >&2
git diff --cached --check
EOF
chmod +x .git/hooks/pre-commit
test -x .git/hooks/pre-commitFail on purpose
printf 'trailing space \n' >> README.md
git add README.md
git commit -m "docs: should fail the hook"Expect a non-zero exit and no new commit. git log -1 --oneline is unchanged.
Pass
git restore --staged README.md
git restore README.md
echo "hooks lab" >> README.md
git add README.md
git commit -m "docs: hooks lab"
git statusClean status, new commit. Remove the hook when you are done with the lab, or leave it — --check is a good default:
rm -f .git/hooks/pre-commitLeave it in place if you want the check on this clone.
Next: submodules (a repo inside a repo) and worktrees (a second working directory, same .git).