2

For the last 20-30 commits, I've been in detached head state:

> git status
HEAD detached from ac83503
nothing to commit, working tree clean

I initially didn't pay attention that I'm in this state. Now I'd like this detached head to become my main branch, and so I give it a name

> git branch the-good-one

That last command provides no feedback, but it appears it's now all right: git log | head -1 shows:

fc876a2 Tue Mar 7 23:10:14 2017 (HEAD, the-good-one) This is the commit message.

and yet git status still replies with:

HEAD detached from ac83503
nothing to commit, working tree clean

Is assigning a git branch name not sufficient to undo a detached head state?

Community
  • 1
  • 1
Calaf
  • 8,925
  • 11
  • 53
  • 110

1 Answers1

5

git branch only creates a branch, it doesn't do a checkout. Do git checkout the-good-one to check the newly created branch out.

A shorthand for creating and checking out at the same time is git checkout -b <branchname>

Trying to clarify things after the edit:

Your starting point is a detached head state (which is unusual by the way, maybe there is something strange in your workflow?). So, your HEAD points to some commit, let's call it a. You then create a new branch with the command git branch the-good-one. Without any further arguments, it creates the branch on the current HEAD, so the newly created branch will also point to a.

Your confusion seems to be here: just because your current (detached) HEAD happens to point to the same commit as the new branch, it doesn't mean that you are currently on the new branch. So if you, say, create a new commit, the-good-one will still point to a, and not to the newly created commit.

Rule of thumb: never do any actual work in detached head state. It's useful if you want to test an older revision, but if you need to make changes, always create (and checkout) a branch.

1615903
  • 28,988
  • 11
  • 62
  • 87
  • But in normal git usage it's entirely redundant to checkout the commit on which one is currently sitting (fc876a2, in this case). Yet here you seem to suggest doing exactly that. I don't much doubt that your suggestion is accurate. I just want to understand what is happening. – Calaf Mar 08 '17 at 15:25
  • I suggest here that you actually check out a branch instead of just creating it and then proceeding to work with a detached head. I don't see how that is redundant. – 1615903 Mar 08 '17 at 16:25