0
0
Gitdevops~5 mins

pre-push hook in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to check your code or run tests before sending it to a shared place. A pre-push hook is a small script that runs automatically before your code is pushed. It helps catch problems early and keeps the shared code safe.
When you want to run tests automatically before pushing code to avoid breaking the shared project.
When you want to check code style or formatting before sending your changes.
When you want to prevent pushing secrets or sensitive data by mistake.
When you want to remind yourself or your team to update documentation before pushing.
When you want to block pushes if certain conditions are not met, like commit message format.
Commands
Create a pre-push hook script that runs tests using npm before pushing code.
Terminal
echo '#!/bin/sh
npm test' > .git/hooks/pre-push
Expected OutputExpected
No output (command runs silently)
Make the pre-push hook script executable so Git can run it automatically.
Terminal
chmod +x .git/hooks/pre-push
Expected OutputExpected
No output (command runs silently)
Try to push your code to the main branch. The pre-push hook runs tests first and blocks push if tests fail.
Terminal
git push origin main
Expected OutputExpected
Running tests... Test suite passed. To github.com:user/repo.git abc1234..def5678 main -> main
Key Concept

If you remember nothing else from this pattern, remember: a pre-push hook runs a script automatically before pushing code to catch problems early.

Common Mistakes
Not making the pre-push hook script executable.
Git will not run the script if it is not executable, so the hook does nothing.
Always run chmod +x on the hook script after creating or editing it.
Writing a hook script with syntax errors or wrong commands.
The hook will fail silently or block pushes unexpectedly.
Test your hook script manually in the terminal before relying on it.
Assuming the hook runs on all machines automatically.
Hooks are local to each Git clone and are not shared by default.
Share hook scripts via a setup script or use tools like Husky for JavaScript projects.
Summary
Create a pre-push hook script inside .git/hooks/pre-push to run checks before pushing.
Make the script executable with chmod +x so Git can run it.
When you push, the hook runs automatically and can block the push if checks fail.