Git - How to prevent a branch to be pushed

Comment on Mastodon

Introduction

I was looking for a simple way to prevent pushing a specific git branch. A few searches on the Internet didn't give me good results, so let me share a solution.

Hooks

Hooks are scripts run by git at a specific time, you have the "pre-" hooks before an action, and "post-" hooks after an action.

We need to edit the hook "pre-push" that happens at push time, before the real push action taking place.

Edit or create the file .git/hooks/pre-push:

#!/bin/sh

branch="$(git branch --show-current)"

if [ "${branch}" = "private" ]
then
    echo "Pushing to the branch ${branch} is forbidden"
    exit 1
fi

Mark the file as executable, otherwise it won't work.

In this example, if you run "git push" while on the branch "private", the process will be aborted.