Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to protect a git branch locally?

Tags:

git

I'm evaluating someone else's git repository and I don't want to make accidental committed changes.

Is there a way to protect a branch locally just by using 'plain Git'? For example by preventing commit to particular branch?

I only need this to affect my local clone.

No Github or other git hosting service features should be involved. I want this to be as portab as possible.

like image 859
bluearth Avatar asked Oct 12 '25 12:10

bluearth


1 Answers

You could use a git hook. Place the following script into .git/hooks/pre-commit :

#!/bin/bash

current_branch="$(git branch --show-current)"
for protected_branch in "main" "other_branch_you_want_protected"; do
    if [[ "$protected_branch" == "$current_branch" ]]; then
        echo "ERROR: local branch $current_branch is protected" 
        exit 1
    fi
done

exit 0

On Linux, don't forget to chmod +x the script file.

like image 116
ChrisB Avatar answered Oct 14 '25 06:10

ChrisB