Git hooks are scripts that Git runs automatically at specific points in the commit or push lifecycle, letting teams enforce standards and automate checks without relying on developers to remember to run them manually.
Key Points: • Client-side hooks like pre-commit and commit-msg run on a developer's own machine, catching issues such as linting failures or malformed commit messages before a commit is even created. • A pre-push hook can run the test suite locally, blocking a push if tests fail before the code ever reaches CI. • Server-side hooks like pre-receive and post-receive run on the Git server, enforcing rules (like blocking force pushes to main) or triggering downstream automation such as CI builds. • Because hooks run automatically, they remove the need for manual reviews to catch simple, mechanical issues like formatting or missing tests. • Tools like Husky (for Node projects) or simple shell scripts in .git/hooks make hooks easy to standardize and share across a team.
Example: A team adds a pre-commit hook that runs a linter and rejects the commit if there are style violations, catching formatting problems locally instead of letting them show up as failed CI checks minutes later.
Code Example:
#!/bin/sh
# .git/hooks/pre-commit
mvn -q checkstyle:check
if [ $? -ne 0 ]; then
echo "Checkstyle failed, commit aborted."
exit 1
fiInterview Tip: A concise interview answer is:
"Git hooks run scripts automatically at points like commit or push, so a team can enforce linting, tests, or commit message standards without depending on developers remembering to do it manually. That catches problems early, before code even reaches CI."