💾 Archived View for perso.pw › blog › articles › git-hook-prevent-branch.gmi captured on 2024-08-18 at 17:18:51. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2023-05-24)

-=-=-=-=-=-=-

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.