16

I have squashed several commits into one commit. One of the commits before the squash included debug prints and a later commit that was squashed together with it removed those prints. Is there any way to recover them?

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
tba
  • 333
  • 3
  • 15

2 Answers2

37

Yes. Use git reflog and then git checkout the commit hash right before the squash.

Here's an example sequence of events.

git init .
touch Foo1 Foo2 Foo3
git add Foo1
git commit -m 'Adding Foo1'
git add Foo2
git commit -m 'Adding Foo2'
git add Foo3
git commit -m 'Adding Foo3'
git log # Observe all three commits
git rebase -i --root # Squash commits

git reflog 
    87a5159 HEAD@{0}: rebase -i (finish): returning to refs/heads/master
    87a5159 HEAD@{1}: rebase -i (squash): Adding Foo1
    a0eecf4 HEAD@{2}: rebase -i (squash): # This is a combination of 2 commits.
    4142aa5 HEAD@{3}: rebase -i (pick): Adding Foo1
    85ad082 HEAD@{4}: rebase -i (pick): Adding Foo1
    cbc3a0c HEAD@{5}: rebase -i (start): checkout cbc3a0c02d1899dcfcc614afc07b3a5a502af56f
    71697f7 HEAD@{6}: commit: Adding Foo3

git checkout HEAD@{6} # get back original commits, with head detached.
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • 3
    I'm glad this answer is still helpful! :) – merlin2011 Apr 29 '20 at 01:54
  • Is there a way to get the commit before squashing from a different machine? – soninob Jun 20 '23 at 12:09
  • @soninob The reflog is local and not shared with remotes, so this trick wouldn't work on a different machine unless the local repo was zipped up in its entirety and copied to a different machine. – merlin2011 Jun 25 '23 at 00:13
0

I know this is an old post, but maybe someone else will find this relevant.
In case you are trying to get a commit id that is in the remote and you don't have it locally.... meaning:
Someone else pushed some commits to a feature branch, and then a PR was opened against develop branch, and a squash strategy was made. You can see the commit id but your local git is not familiar with this ref.
All you need to do is:
git fetch <commit_id> and all its tree will be available.
We are using bitbucket as our git server, curl to the PR returning in the data's latest commit digest. From that point, it was easy to retrieve all data relevant

soninob
  • 428
  • 11
  • 22