I am working on a branch in git. When I do
git checkout
(commit id obtained from git log
), it is getting commit
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.
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.
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.
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.
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.
If you checkout
a commit sha directly, it puts you into a "detached head" state, which basically just means that the current sha that your working copy has checked out, doesn't have a branch pointing at it.
If you haven't made any commits yet, you can leave detached head state by simply checking out whichever branch you were on before checking out the commit sha:
git checkout <branch>
If you did make commits while you were in the detached head state, you can save your work by simply attaching a branch before or while you leave detached head state:
# Checkout a new branch at current detached head state:
git checkout -b newBranch
You can read more about detached head state at the official Linux Kernel Git docs for checkout.
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.