Git Hooks
You'll learn how to automate actions at key moments in your Git workflow using hooks that run scripts before or after Git events.
What Are Git Hooks?
Git hooks are custom scripts that Git automatically executes when certain events occur—like committing, pushing, or merging. Think of them as event listeners for your repository: whenever Git performs a specific action, it checks if there's a hook script to run first or afterward.
Client-Side vs Server-Side Hooks
Client-side hooks run on your local machine during operations like committing or merging. Common examples include:
pre-commit– runs before a commit is finalized (perfect for linting or running tests)commit-msg– validates your commit message formatpre-push– executes before pushing to a remote (can prevent bad code from leaving your machine)
Server-side hooks run on the remote repository during push operations:
pre-receive– runs before any refs are updated (can reject pushes that violate policies)update– similar to pre-receive but runs per branchpost-receive– runs after refs are updated (useful for deployment or notifications)
How They Work
Hooks live in .git/hooks/ as executable scripts. Git includes sample hooks (ending in .sample) that you can rename and customize. Write them in any scripting language your system supports—bash, Python, Ruby, etc.
If a pre-event hook exits with a non-zero status, Git aborts the operation. This gives you veto power over commits, pushes, and merges that don't meet your standards.
Key Takeaway: Git hooks automate quality checks and workflows by running custom scripts at critical points in the Git lifecycle, enforcing standards on both client and server sides without manual intervention.