Git Hooks
Git Hooks: Running Automated Scripts on Git Events
Git hooks are executable scripts stored inside .git/hooks/ that Git runs automatically before or after events such as committing, writing a commit message, or pushing. Teams use hooks to catch formatting mistakes, failing tests, or accidental .env secrets before a bad commit is even created.
Common Client-Side Hooks You Will Use
Git ships sample scripts in .git/hooks/ ending in .sample. Removing .sample and marking a script executable activates it:
pre-commit: Runs right when you executegit commit, before Git asks for a message. Ideal for code formatters, linters, or fast unit tests. Exit non-zero to abort the commit.commit-msg: Inspects your commit message file (such as enforcing Conventional Commits likefeat: add banner.svg).pre-push: Runs beforegit pushtransfers commits, ideal for slower full test suites.
Writing a Simple pre-commit Hook
Create .git/hooks/pre-commit to block commits that accidentally leave console.log or conflict markers in staged files:
#!/usr/bin/env bash
if git diff --cached --name-only | grep -qE '\.env$'; then
echo "Blocked: never commit .env files."
exit 1
fi
Make the hook executable on macOS, Linux, or Git Bash:
chmod +x .git/hooks/pre-commit
Sharing Hooks Across Your Team
Because .git/ is never pushed to GitHub, local scripts in .git/hooks/ stay on one machine unless you track a shared hooks folder in your repository (for example .githooks/) and configure Git or tooling like Husky or pre-commit:
git config core.hooksPath .githooks
Common Hook Mistakes
Remember that developers can bypass local hooks anytime with git commit --no-verify. Always enforce critical checks in server-side CI/CD as well—local hooks are a speed helper, not a security wall.
Frequently Asked Questions
Why is my pre-commit hook ignored when I commit?
Usually the file still ends in .sample, or it lacks executable permissions (chmod +x .git/hooks/pre-commit). Also double-check the top #!/usr/bin/env bash shebang line.
Can I write Git hooks in Node.js or Python instead of Bash?
Yes. Any executable script works—just start the file with #!/usr/bin/env node or #!/usr/bin/env python3 and return a non-zero exit code to block the action.
How do I temporarily bypass a failing pre-commit hook?
Pass --no-verify (-n), such as git commit --no-verify -m "Save emergency fix". Use this sparingly so broken code does not enter shared branches.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With