tags:

views:

72

answers:

3

Let's say I have committed many times. Now I want to come back to a certain commit and view how my working directory looked like at that time (I actually want my working directory to change when I do it). And finally go back to original head without messing up my commits?!

I know it should be easy to do it, I'm just can't seem to find the right command. Thank you.

+1  A: 
git checkout <sha of old commit>

Then when you're done, just git checkout master or wherever you want to be.

dahlbyk
+5  A: 

To check out a given commit, use git checkout:

git checkout <SHA1 of commit>

To return to your original branch, check it out:

git checkout master

A couple notes:

  • If you have uncommitted modifications, the checkout will probably fail. You might want to commit or stash them first.

  • When you check out something which is not a branch, you end up in detached HEAD state; that is, your HEAD doesn't refer to a branch - surprise! This means that in particular, if you make a commit, it won't be on a branch. Make sure to check out a branch if you want to commit. If your intent is to make a commit off of the one you're checking out, you can check it out and create a branch at the same time: git checkout -b new-branch <SHA1 of commit>

Jefromi
Err... one final note: `git checkout -- afile` will erase any local change you could currently have on that file in your working directory, *without any notification*. `git checkout abranch` won't. And pray you don't have a file in the current directory named like the branch you want to checkout. See http://stackoverflow.com/questions/2961240/get-back-the-changes-after-accidental-checkout/2961348#2961348. One of my true gripe with Git (that and the dramatic slowdown of `git status` when there are submodules with 1.7+)
VonC
@VonC: Well, not checking out individual files in this case, but good points.
Jefromi
yeap, that's it. Thank you. I wonder why there isn't a word about it in the git community book. There are merely examples of using 'checkout' to switch between branches..
Dziamid
@Dziamid: Well, a branch is in a way just a specific case. It checks out commits, and a branch is a pointer to a particular commit.
Jefromi
+1  A: 

Creating a detached HEAD as in Jefromi's answer may do what you want.

We can give you more helpful answers if you tell us your underlying motivation. For example, if the commit in question was a significant milestone, then maybe you want to tag it to give it a meaningful name:

git tag -a -m 'Release 1.0' v1.0 <sha1>

Other possibilities:

  • Create and switch to a branch at that point
git checkout -b my-branch-name <sha1>
  • View the contents of a particular file from that commit
git show <sha1>:foo.c
  • See everything that has changed since that commit
git diff <sha1> HEAD
  • See changes in a particular file
git diff <sha1> HEAD -- xyz.cpp
Greg Bacon