Hoytman
Hoytman

Reputation: 1812

How do I keep from losing commits if I check out an earlier commit?

How do I keep from losing commits if I check out an earlier commit? I want to go back and look at an earlier state that I committed a few days ago.

I got the message: you are leaving one commit behind, not connected to any of our branches. I got this by checking out head, committing, then checking out master.

Upvotes: 0

Views: 160

Answers (2)

achedeuzot
achedeuzot

Reputation: 4384

You can access a previous commit by using a git checkout <checksum>.

Git will warn you that you are in detached HEAD state, but don't worry, you others commits are not lost. You can look around and when you are finished, you can git checkout the branch you were on to start with to get back to where you were.

A good way to see where you are when you are doing this is by using the git branch command.

Example:

>$ (...) demo setup (...)
>$ git branch
* master
>$ git log
commit c69905e97e0975810a7b35ca1adf872e9e916758
[...]
Commit again

commit a9d5d2f5ad39036093048750ecffeb570875611b
[...]
First commit
>$ git checkout a9d5d2f
Note: checking out 'a9d5d2f'.

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 a9d5d2f... First commit
>$ git branch
* (detached from a9d5d2f)
  master
>$ (...) look at my files, do some stuff (...)
>$ (...) I can make some commits here and make a new branch with them - see above git message (...)
>$ git checkout master # I'm back to the original state
>$ git branch
* master

Voilà !

Upvotes: 2

Nikhil Gupta
Nikhil Gupta

Reputation: 1778

A git checkout HEAD~10 -- <path to file> would overwrite the existing file to that version in your local copy. This would not mean that you have lost your changes unless you commit this back, in which case as well you still have your original commit in git which you can get back.

If you want to compare two commits use git diff not git checkout.

Upvotes: 0

Related Questions