Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I ever git checkout --detach

Tags:

git

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?

like image 447
jkulak Avatar asked Nov 20 '16 20:11

jkulak


People also ask

What does git checkout -- detach do?

When you choose to checkout a commit hash, or a branch with --detach, any commits made will not belong to a specific branch.

What causes detached head in git?

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.

What is git detach?

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.

How do I fix a detached head in git?

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.


1 Answers

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.

like image 126
Oliver Charlesworth Avatar answered Sep 28 '22 02:09

Oliver Charlesworth