Git Hooks

Git hooks are scripts triggered by Git lifecycle events. Client-side hooks can run before commits, after commits, before pushes, and during other operations. Teams often use hooks to run formatting, linting, tests, or validation.

Hooks are local by default and are not automatically versioned simply because they exist in .git/hooks.

Simple Pre-Commit Hook
# .git/hooks/pre-commit
#!/bin/sh
npm test
if [ $? -ne 0 ]; then
  echo "Tests failed. Commit aborted."
  exit 1
fi
💡 A non-zero exit code from the pre-commit hook prevents the commit. Teams often use hook-management tools when hooks need to be shared consistently.
Key Takeaways
  • Hooks can enforce local development checks.
  • Client-side hooks can be bypassed or may not exist on every developer machine.
  • Critical validation should also run in CI.
Knowledge Check

Which hook commonly runs before a commit is created?