Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to protect a git branch locally?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading