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.
.git/hooks directoryHooks are plain executable scripts. Git looks for a file with the hook name (without .sample) and executes it at the correct lifecycle stage.
# Run a linter before committing
#!/bin/sh
npm run lint
# Make the pre-commit hook executable
chmod +x .git/hooks/pre-commit
If the linter or test fails, Git cancels the commit or push. This ensures only validated code reaches the repository.
Try modifying your commit message format and observe how the commit-msg hook blocks invalid commits.
# 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