DEV Community

Michele Caci
Michele Caci

Posted on

How to create an orphan branch in git

Sometimes you may need to create a brand new branch on a git project that doesn't contain anything present on the other branches nor shares an history with them, called orphan branch.

This snippet describes how to do it:

BRANCH_NAME=$1
git checkout --orphan $BRANCH_NAME
git rm -rf .
rm .gitignore
echo "# $BRANCH_NAME" > README.md
git add README.md
git commit -m "Initial commit for branch $BRANCH_NAME"
git push origin $BRANCH_NAME
Enter fullscreen mode Exit fullscreen mode

This snippet can be used as a sequence of commands, replacing $1 with any value for the branch name, or in a bash script, for example naming it orphan_branch.sh and running it with sh ./orphan_branch.sh new_branch_name.

More information can be found in the git reference guide at the git checkout documentation.

Top comments (5)

Collapse
 
slavius profile image
Slavius

Hello, nice article. Could you please elaborate on what are the use cases to use orphan branches? Thanks.

Collapse
 
mcaci profile image
Michele Caci

Hi, thank you! At the moment I don't know any use cases, I have heard some examples of putting code in one branch and CI deployment code in an orphan branch, but that is as far as my knowledge goes for now. For this example I just have done a test myself to experiment and see how to build them and what they look like

Collapse
 
slavius profile image
Slavius

Hi, I actually found one example directly in the git man page for git-checkout:

This can be useful when you want to publish the tree from a commit without exposing its full history. You might want to do this to publish an open source branch of a project whose current tree is "clean", but whose full history contains proprietary or otherwise encumbered bits of code.

Thread Thread
 
mcaci profile image
Michele Caci

Cool, that's a great spotting! I didn't read the full piece of the git man page for the --orphan flag and now I have learned something new on top of what I wrote. Thanks for your comments!

Collapse
 
brunoelo profile image
Emeka Elo-Chukwuma

Where I have been able to utilize this is in a course I'm taking. I want all the parts of the course to be done in a single repo so I'm making each part an orphan branch.

P.S. some parts are not all related.