I ran the git log --oneline
command and then ran the git checkout <commit-id>
of some previous commit. I got the message that the "HEAD is now in the detached state...". Now I do not know how to get back to the latest commit. What is the command to get back to the latest commit. And when do we use this feature to checkout a previous commit version. Please let me know as I ran the checkout command while I was exploring git. Also how can we know to which commit the HEAD
is pointing to?

- 3,451
- 8
- 52
- 105
2 Answers
To return to your 'latest' commit checkout the branch you were working on. Either
git checkout master
or any other branch
git checkout <my_branch>
Checking previous commit or any commit which is not in a branch gets you in Detached HEAD state. This is valid state in git. Your working directory is updated and you can develop. What you cannot do in this state is perform commits. If you want to continue developing from some historical you can branch out from there. Example:
git checkout <some_hash_in_the_past>
... Detached head
git branch <my_new_branch>
... edit files
git add/commit

- 13,146
- 5
- 30
- 48
Just check out the branch you want to be on.
git checkout <branch name>
git checkout master
As to when you want to check out a previous commit can be alot of things. For example if you want to know when a bug was introduced you can check out older versions and see if the bug is present there.
HEAD is the commit you are currently on. You can get the commit id with this.
git rev-parse HEAD
If you want the latest commit of a branch i.e master
git rev-parse master

- 11,077
- 3
- 36
- 46