← Back to Chapters

Git Hooks

? Git Hooks

? Quick Overview

Git hooks are scripts that Git executes before or after events such as commits, merges, and push actions. They help automate checks, enforce rules, and integrate workflows directly into the Git lifecycle.

? Key Concepts

  • Hooks are stored inside the .git/hooks directory
  • They run automatically on specific Git events
  • They can block actions if conditions fail
  • Written in shell, Bash, or any scripting language

? Syntax / Theory

Hooks are plain executable scripts. Git looks for a file with the hook name (without .sample) and executes it at the correct lifecycle stage.

? Code Examples

? View Code Example
# Run a linter before committing
#!/bin/sh
npm run lint
? View Code Example
# Make the pre-commit hook executable
chmod +x .git/hooks/pre-commit

? Live Output / Explanation

If the linter or test fails, Git cancels the commit or push. This ensures only validated code reaches the repository.

? Interactive Example

Try modifying your commit message format and observe how the commit-msg hook blocks invalid commits.

? View Code Example
# Validate commit message format
#!/bin/sh
commit_regex='^Issue #[0-9]+: .+'
if ! grep -qE "$commit_regex" "$1"; then
echo "Invalid commit message"
exit 1
fi

? Use Cases

  • Running tests before commits
  • Enforcing commit message standards
  • Preventing broken code from being pushed
  • Triggering notifications or scripts

? Tips & Best Practices

  • Keep hooks fast to avoid slowing developers
  • Test hooks locally before team adoption
  • Use tools like Husky for easier management

? Try It Yourself

  • Create a pre-commit hook to run tests
  • Add a commit-msg hook for format checks
  • Experiment with pre-push validation