Recovering lost commits with git reflog

If you ran git reset --hard or deleted a branch by mistake, the commits are still there. Find them again with git reflog.

1 min read

If git reset --hard or git branch -D made you lose commits, they usually aren’t truly gone. Git keeps those commits around for a while, and git reflog records every place HEAD has pointed to, so you can find them again.

For example, say you’re on the fix/export-csv branch with three unpushed commits, and you accidentally run:

git reset --hard origin/main

Look at the reflog:

git reflog
9e2f1ab HEAD@{0}: reset: moving to origin/main
4c07d1e HEAD@{1}: commit: export csv: escape dau phay
b81a9f3 HEAD@{2}: commit: export csv: them cot ngay tao
27de5c0 HEAD@{3}: commit: export csv: ban dau
9e2f1ab HEAD@{4}: checkout: moving from main to fix/export-csv

The topmost commit before the reset is 4c07d1e. Create a new branch pointing to it:

git branch fix/export-csv-cuu 4c07d1e

The three commits are back on the fix/export-csv-cuu branch. If you want to move your current branch straight back to that state, use git reset --hard 4c07d1e, or git reset --hard 'HEAD@{1}'. In zsh you have to quote HEAD@{1}.

A branch deleted with git branch -D can be recovered the same way. The delete command prints the branch’s last hash:

Deleted branch fix/export-csv (was 4c07d1e).

Run git branch fix/export-csv 4c07d1e and the branch is back. If you’ve already lost that line, look for the hash in git reflog.

Note: the reflog lives only on your local machine and is not pushed. Old entries also expire on their own: by default 30 days for entries no branch points to anymore, and 90 days for entries still reachable from the current branch. Uncommitted changes wiped by reset --hard are not in the reflog and can’t be recovered.