When you checkout a direct commit name (using the SHA-1 hash of the commit object) instead of checking out a branch name, you end up with a “detached HEAD”. HEAD is the “ref” that keeps track of what is currently checked out. It becomes detached when you directly checkout a commit instead of a branch (it is not attached to any branch). No branches are updated when you detach a repository's HEAD. You might think of the detached head state as if you had an anonymous branch checked out.
To reattach your repository's HEAD, you will want to save the current HEAD as a branch and check that branch out:
To save the current HEAD in a new branch do this:
git branch <new-branch-name>
To overwrite an existing branch you need to use --force
:
git branch --force <existing-branch-name>
Then, reattach your repository's HEAD by checking out the new/updated branch:
git checkout <branch-name>
(where <branch-name>
is the same as <new-branch-name>
or <existing-branch-name>
, depending on which of the above two commands you used)
This sequence (git branch
to make a ref point to the current HEAD commit, then git checkout
that updated branch) will carry forward any uncommitted content that you might have in your working index and/or tree.
In the future, if you want to ‘roll back’ the current branch to some previous commit, you should use this instead of detaching your repository's HEAD:
git reset --hard <commit>
This will reset the current branch (or your detached HEAD, if it is already detached) to the named commit, and make the index and the working tree reflect that commit (i.e. it throws away any commits since the specified commit along with any uncommitted content).
The detached HEAD state is useful for revisiting old states, and sometimes for short-term work that you are not sure you will keep. Other than that you probably want to avoid it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…