I understand what's happening under the hood, when I run $ git checkout --detach
.
While on master
, when I $ git checkout --detach
, my .git/HEAD
is not pointing to ref: refs/heads/master
but to a hash instead (same a as refs/heads/master
).
What would be the use case, when I would actually want to do that?
When you choose to checkout a commit hash, or a branch with --detach, any commits made will not belong to a specific branch.
Any checkout of a commit that is not the name of one of your branches will get you a detached HEAD. A SHA1 which represents the tip of a branch still gives a detached HEAD. Only a checkout of a local branch name avoids that mode. When HEAD is detached, commits work like normal, except no named branch gets updated.
A “detached HEAD” message in git just means that HEAD (the part of git that tracks what your current working directory should match) is pointing directly to a commit rather than a branch. Any changes that are committed in this state are only remembered as long as you don't switch to a different branch.
If you want to keep changes made with a detached HEAD, just create a new branch and switch to it. You can create it right after arriving at a detached HEAD or after creating one or more commits. The result is the same. The only restriction is that you should do it before returning to your normal branch.
According to the commit that introduced the flag:
For example, one might use this when making a temporary merge to test that two topics work well together.
I guess the idea is that deliberately detaching allows you to then make further commits that you know will be discarded once you're done (and once GC has run).
Note that this flag doesn't actually add any new functionality; you could achieve the same result previously with git checkout some-branch^0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With