Git hooks are scripts that automatically execute when specific Git events (commits, pushes, etc.) occur. By using them, you can apply custom rules to your development workflow. Here, I’ll explain how to prohibit direct git push to the main branch in your local environment.
Creating the pre-push Hook
The pre-push hook is executed just before the git push command sends data to the remote repository. If this hook returns a non-zero exit code, the push operation is aborted.
Navigate to the
.git/hooksdirectory: Move to the.git/hooksdirectory at the root of your Git repository.cd .git/hooksCreate the
pre-pushscript: Create a file namedpre-pushwith the following content:#!/bin/bash # Get the current branch name current_branch=$(git symbolic-ref HEAD --short) # If the current branch is 'main', display an error message and prohibit the push if [ "$current_branch" = "main" ]; then echo "Error: Direct push to 'main' branch is not allowed." echo "Please create a new branch and open a pull request." exit 1 # Returning a non-zero exit code aborts the push fi # For any other branch, allow the push exit 0#!/bin/bash: Specifies that the script should be executed with Bash.git symbolic-ref HEAD --short: Gets the current branch name.if [ "$current_branch" = "main" ]; then ... fi: Checks whether the current branch ismain.echo "Error: ...": Displays an error message to standard output.exit 1: Aborts the push operation.exit 0: Continues the push operation.
Grant execute permission: Grant execute permission to the created script.
chmod +x pre-push
Now, if you try to execute git push while on the main branch, an error message will be displayed and the push will be rejected.
Notes
- Local only: Git hooks only apply to the local repository. To enforce rules in team development, you need to combine server-side hooks (e.g., GitHub branch protection rules) or CI/CD pipeline checks.
- Hook bypass: Using the
git push --no-verifyoption allows pushing while bypassing Git hooks. Therefore, hooks should be positioned as supplementary tools to prevent developer mistakes.
By setting up this hook, you can prevent accidentally pushing changes directly to the main branch and promote a safer development workflow.