Preventing Direct Push to Main Branch Using Git Hooks

How to implement a Git pre-push hook that prevents direct pushes to the main branch, with a step-by-step shell script setup guide and important caveats.

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.

  1. Navigate to the .git/hooks directory: Move to the .git/hooks directory at the root of your Git repository.

    cd .git/hooks
    
  2. Create the pre-push script: Create a file named pre-push with 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 is main.
    • echo "Error: ...": Displays an error message to standard output.
    • exit 1: Aborts the push operation.
    • exit 0: Continues the push operation.
  3. 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-verify option 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.