[git] "git checkout <commit id>" is changing branch to "no branch"

I am working on a branch in git. When I do

git checkout <commit id>

(commit id obtained from git log ), it is getting committed to that particular change but branch is changed to <No-branch>.

Why is this happening? How do you resolve this?

This question is related to git

The answer is


By checking out to one of the commits in the history you are moving your git into so called 'detached state', which looks like is not what you want. Use this single command to create a new branch on one of the commits from the history:

git checkout -b <new_branch_name> <SHA1>

If you are branch master and you do a git checkout <SHA>

I'm fairly certain that this causes git to load that commit in a detached state, changing you out of the current branch.

If you want to make changes you can and then you can do a git checkout -b <mynewbranch> to create a new branch based off that commit and any changes you have made.


This worked best for me when I wanted to check out the code, given the commit ID <commit_id_SHA1>

git fetch origin <commit_id_SHA1>
git checkout -b new_branch FETCH_HEAD

Other answers have explained what 'detached HEAD' means. I try to answer why I want to do that. There are some cases I prefer checkout a commit than checkout a temporary branch.

  1. To compile/build at some specific commit (maybe for your daily build or just to release some specific version to test team), I used to checkout a tmp branch for that, but then I need to remember to delete the tmp branch after build. So I found checkout a commit is more convenient, after the build I just checkout to the original branch.

  2. To check what codes look like at that commit, maybe to debug an issue. The case is not much different from my case #1, I can also checkout a tmp branch for that but then I need to remember delete it. So I choose to checkout a commit more often.

  3. This is probably just me being paranoid, so I prepare to merge another branch but I already suspect I would get some merge conflict and I want to see them first before merge. So I checkout the head commit then do the merge, see the merge result. Then I git checkout -f to switch back to my branch, using -f to discard any merge conflict. Again I found it more convenient than checkout a tmp branch.


Is that commit in the other branch? Git checkout <commitid> will just switch over to the other branch if the commit has happened in the other branch. You will want to merge the changes to your first branch if you want the code there.