Ajil Raju
Ajil Raju

Reputation: 37

git checkout <commit hash>

How to use git checkout for the previous commit? Problem: I have 3 commit like A, B and C ( C is the last commit) A <- B <- C I want to go my previous version of the project that is the commit A, then is using git checkout <A hash> now I'm in commit A, after that I want to go commit B, I want the commit hash git log that is not displaying, then I want to switch back to commit B and C one after another.

Upvotes: 3

Views: 10590

Answers (3)

Statham
Statham

Reputation: 4118

You can use

git reflog

to show it.

Upvotes: 2

William Pursell
William Pursell

Reputation: 212248

I think the problem you are describing is that once you have done a checkout at commit A, you are having difficulty finding the hash of commit C that you want to go back to. The easiest thing to do is to create a branch or tag at commit C before you checkout commit A. But if you didn't do that, git reflog to the rescue:

$ git init
$ for i in a b c; do echo $i > file; git add file; git commit -m "Write $i to file"; done
[master (root-commit) 0d89e41] Write a to file
 1 file changed, 1 insertion(+)
 create mode 100644 file
[master a8f774a] Write b to file
 1 file changed, 1 insertion(+), 1 deletion(-)
[master c52fd0c] Write c to file
 1 file changed, 1 insertion(+), 1 deletion(-)
$ git log --pretty=oneline
c52fd0c4ae9fb40b4e7355c7a2f8ecbe80d9465c (HEAD -> master) Write c to file
a8f774a88af68481db6106f1d613680769c1cde9 Write b to file
0d89e41907055d75ac8c65d40feec4fc1ee9e381 Write a to file
$ git checkout HEAD~2
Note: checking out 'HEAD~2'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 0d89e41... Write a to file
$ # Oh no!  I can't figure out the hash of commit C
$ git reflog
0d89e41 (HEAD) HEAD@{0}: checkout: moving from master to HEAD~2
c52fd0c (master) HEAD@{1}: commit: Write c to file
a8f774a HEAD@{2}: commit: Write b to file
0d89e41 (HEAD) HEAD@{3}: commit (initial): Write a to file

Now, to get back to commit C, you can reference it either as c52fd0c or as HEAD@{1}. (The latter will change as you make modifications to the history, with the number in braces incrementing each time.)

Upvotes: 1

merlin2011
merlin2011

Reputation: 75565

If you want to get the commits from a particular commit, you can give the branch name to git log. If your main branch is master, the following command will get you the hashes you want.

git log master

Upvotes: 2

Related Questions