Suppose you just goofed and think you lost some changes. Here’s a step-by-step guide in order to maximize their chance of being recovered. If you’re not already there, go to your Git repository’s directory in your favorite shell, and we’ll commence:
-
git status
to see what Git says. If you’re unfamilar with Git, do this after each step. -
git diff
to see if your changes aren’t actually lost at all. -
git fsck --lost-found
to save dangling commits and objects into.git/lost-found/commit
(and/other
).-
This may happen if you
git add
changes (and so create a blob) and thengit reset --hard
, discarding the staged changes. -
Inspect the commits in
.../commit
with Git show, and if you find what you’re looking for, merge or cherry-pick it. -
Search the files in
.../other
with grep (or better, rg) for your lost changes. They’re objects Git has in its database but can’t find from any reference. If this is where you find your lost work, you’ll need to manually graft them into your working copy (say, by replacing the corresponding file and then staging interactively).
-
-
git reflog
to review the chronological history of your actions with Git.-
This displays the logged changes of the reference
HEAD
(whatgit status
reports as the current branch), which is roughly equivalent to changes in the repository’s state. -
You can browse all the changes as patches with
git reflog --all -p
, and then search through the output. -
You should study the reflog and get a sense of your recent actions to help determine when your changes were lost.
-
If you find you just need to go “back in time,” you can reset your branch.
-
Writing this post made me realize “reflog” is a portmanteau of “reference log.” I’ve been pronouncing it wrong.
-
-
git stash list
to see if you stashed the changes.-
git show stash@{0} --patch
to see each stash. -
I had to escape it as
stash@\{0\}
in Zsh.
-
-
git branch --all
to look for a suspicious new branch. -
git log -G<regex> --patch
to search the history of changes.-
The changes could easily have been added to a recent commit without being noticed. Do some code sleuthing.
-
If you wish, rewrite your history and clean it up.
-
You should really clean up before you push.
-
I hope this helped. Git does an excellent job not losing changes, but it can’t stop every mistake. Good luck with your search.