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?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Black
  • 18,150
  • 39
  • 158
  • 271

1 Answers1

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.

Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154