Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Git, how can I recover a staged file that was reverted prior to committing?

Tags:

git

git-tower

I was attempting to pull a change into my repository using Git Tower. When I did so, there was a conflict and I mistakenly hit stage all (as I wanted to commit after resolving the conflict). When I did so, the conflict marked itself as resolved.

I wanted to manually resolve the change so I hit "Abort Merge", however, when I did this, It rolled back all my changes! Is there any way to get them back?

like image 833
David Avatar asked Jun 19 '12 05:06

David


People also ask

How do I restore a file in git?

Recovering Deleted Files with the Command Line Git provides ways to recover a deleted file at any point in this life cycle of changes. If you have not staged the deletion yet, simply run `git restore <filename>` and the file will be restored from the index.

How do you restore a file in a commit?

If your commit was used to delete the file you are trying to recover, just use shacommit~1 (ex: git checkout 0f4bbdcd~1 -- path/to/file. txt ) to get the commit immediately before.

How do I see changes to a staged file in git?

If your changes are already staged, then there's no difference to show. But there's a command line option that will show you staged changes if you specify it: git diff --staged . With the --staged option, git diff will compare your staged changes against the previous commit.


1 Answers

If you had anything staged to git, you probably should be able to get that back. (If you just changed working copy, you wouldn't be able to restore it.)

First of all: do not run git gc. Backup your repository and working copy before going ahead. (Make sure to backup .git directory.) Also avoid closing terminal where this happened, and/or rebooting — if all fails, you have a chance to find stuff in history / memory.

Anyway, first thing to try is:

 git fsck --lost-found 

It will print something like

 Checking object directories: 100% (256/256), done. Checking objects: 100% (30165/30165), done. dangling blob 8f72c7d79f964b8279da93ca8c05bd685e892756 dangling commit 4993502a6394491190d3f4d6fb3d1e14019c2e9b 

Since you lost staged files and did not do a commit, you're interested in dangling blob entries.

Run git show <sha> for each one — some of them should be your files.

like image 91
Alexander Gladysh Avatar answered Sep 24 '22 19:09

Alexander Gladysh