0

I used the command git checkout 1234567 to view an old commit. Directly afterwards I checked another commit git checkout 1234568 then I checked to master again git checkout master. But now my website is on a old version.

After I executed git log --oneline I realised that my two latest commits are lost! Why did this happen and is it possible to restore them?

Is it because I have to checkout to master again everytime before I checkout to another commit?

4
  • Did you make those two commits on master or while you had checked out one of the other commits? Commented Mar 8, 2016 at 8:10
  • what happens if you try to checkout them again ? did you lose their hash ? Commented Mar 8, 2016 at 8:19
  • Check git reflog to see what commits you have actually checked out Commented Mar 8, 2016 at 8:21
  • @EnricoCampidoglio yes i made these two commits on master. I did not made any commits while checking out the older commits Commented Mar 8, 2016 at 8:38

1 Answer 1

4

In Git, nothing is lost as long as you've committed it1.

You can use the reflog to get a journal of the commits that master has been pointing to through time by saying:

git reflog master 

Once you've located the latest one of your lost commits in the reflog, you can make master point to it again by using git reset.

For example, let's say that the latest lost commit is on the 4th entry in the reflog. In order to restore it on master you would say:

git checkout master git reset --hard master@{4} 

where master@{4} refers to the commit that master was pointing to 4 entries ago from where it is now.

Note that before you reset master, you should make sure that your working directory is clean, that is you don't have any uncommitted changes.


1. Well, almost nothing. Unreachable commits are going to eventually be deleted if enough time passes. By default, they will be kept around for 30 days but you can change that limit through the gc.reflogExpireUnreachable option.

Sign up to request clarification or add additional context in comments.

6 Comments

I just executed git checkout master but my two latest commits are not appearing, it seems like they are really lost.
Did you look in the reflog?
If i execute git reflog then i see my latest commits and their SHA ID again, but im not sure how i can restore the latest commit again.
If you working directory is clean, use git reset --hard <commit-sha>. Please see my answer.
@EdwardBlack Great. If my answer solved your problem, you can tick the check mark on its right to mark it as accepted.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.