search by tags

for the user

adventures into the land of the command line

recover a lost commit with git reflog

imagine you are working on a file:

$ git checkout SOMETHING
$ vim file_a.txt
$ git add file_a.txt
$ git commit -m "committing changes to file_a"

and at the same time, someone else is working on the same file on another branch. the other person merges their changes to the master. you go home, without merging and the next morning, bleary eyed and without yet consuming your first coffee:

$ git status
On branch SOMETHING
.
.
$ git pull origin master
remote: Counting objects: 82, done.
remote: Compressing objects: 100% (32/32), done.
remote: Total 32 (delta 19), reused 0 (delta 0)
Unpacking objects: 100% (32/32), done.
From https://github.com/somegroovyrepo
   dfa09b5..771ab23  master     -> origin/master
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull 

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/ SOMETHING

then you check in your file_a.txt but you see it’s been changed! it’s been updated with someone else’s changes and you’ve lost yours. OH NOES!

how can i get my changes back? you can check the reflog to see a history of the events on the branch:

$ git reflog
16f51b0 [email protected]{0}: checkout: moving from master to SOMETHING
771ab23 [email protected]{1}: checkout: moving from SOMETHING to master
16f51b0 [email protected]{2}: checkout: moving from master to SOMETHING
771ab23 [email protected]{3}: checkout: moving from SOMETHING to master
16f51b0 [email protected]{4}: checkout: moving from master to SOMETHING
771ab23 [email protected]{5}: pull: Fast-forward
dfa09b5 [email protected]{6}: checkout: moving from SOMETHING to master
16f51b0 [email protected]{7}: commit: committing changes to file_a

find the HEAD you want to go back to:

$ git reset --hard 16f51b0
HEAD is now at 16f51b0 committing changes to file_a

….aaaaand we’re back. phew.