What is `git checkout --orphan` used for?

GitGit BranchGit Checkout

Git Problem Overview


I've just discovered git checkout --orphan, but I don't know how to use it. Its help page says it creates a new unparented branch.

In the master branch, I've tried git checkout --orphan br, only to see the files in the working directory change to “Changes to be committed”, and the git log saying fatal: bad default revision 'HEAD'.

So what's the advantage of using git checkout --orphan?

Git Solutions


Solution 1 - Git

The core use for git checkout --orphan is to create a branch in a git init-like state on a non-new repository.

Without this ability, all of your git branches would have a common ancestor, your initial commit. This is a common case, but in no way the only one. For example, git allows you to track multiple independent projects as different branches in a single repository.

That's why your files are being reported as “changes to be committed”: in a git init state, the first commit isn't created yet, so all files are new to git.

Solution 2 - Git

It's used by e.g. GitHub Pages, which stores a repo's website inside the repo but on a separate branch. There's no reason to store anything but the website's history on this branch.

Solution 3 - Git

We were moving to a public repo from a private one and because of sensitive commit information, we wanted to reset a branch as new and push it as a blank branch. Here is a typical way of a workflow for that:

https://stackoverflow.com/questions/13716658/how-to-delete-all-commit-history-in-github

Solution 4 - Git

Another use case where this may be useful is build machines or virtual instances for testing that require specific .git folder settings (e.g. user, remote url) and all history discarded because of space limitations. This is often the case with legacy setups that don't use containers such as Docker.

It would tipically be done for dedicated deployment branches instead of dealing with master. Once the new branch is pushed to remote, on the instance do:

git clone [remote-url] --branch [name] --single-branch [folder]

Shallow clone would be a better option when working directly with master (not recommended):

git clone -–depth [depth] [remote-url]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjsvisaView Question on Stackoverflow
Solution 1 - GitJB.View Answer on Stackoverflow
Solution 2 - GitFred FooView Answer on Stackoverflow
Solution 3 - Gituser1767754View Answer on Stackoverflow
Solution 4 - GitAtanas SariyskiView Answer on Stackoverflow