Recover from losing uncommitted changes by "git reset --hard"
Asked Answered
F

23

686

Is there any way to recover uncommitted changes to the working directory from a git reset --hard HEAD?

Ferrocyanide answered 26/4, 2011 at 8:52 Comment(3)
Not related to Undoing a git reset --hard HEAD~1, because here the original poster is trying to recover uncommitted changes.Chiro
See also Recovering added file after doing git reset --hard HEAD^.Chiro
See also Accidentally reverted to master, lost uncommitted changes.Chiro
D
631

You cannot get back uncommitted changes in general.

Previously staged changes (git add) should be recoverable from index objects, so if you did, use git fsck --lost-found to locate the objects related to it. (This writes the objects to the .git/lost-found/ directory; from there you can use git show <filename> to see the contents of each file.)

If not, the answer here would be: look at your backup. Perhaps your editor/IDE stores temp copies under /tmp or C:\TEMP and things like that.[1]

git reset HEAD@{1}

This will restore to the previous HEAD

[1] vim e.g. optionally stores persistent undo, eclipse IDE stores local history; such features might save your a**

Dennison answered 26/4, 2011 at 8:55 Comment(18)
Eclipse's local history - and in addition, since some changes were older than 6 days, my Time Machine backup of Eclipse's local history! For some reason the Time Machine backup of the folder managed by git did not contain my previous changes.Reiner
Here is the link for instructions as to how to recover files from Eclipse backup. wiki.eclipse.org/…Tanager
Luckily I have TimeMachine set up to backup every hour so I was able to scoop the files out of the last backup. It doesn't recover hidden files so far as I can tell so you should copy the files over directly from the filesystem.Maintenance
It doesn't make sense why git can't just backup uncommitted changes during a reset, even temporarily. This is an entirely preventable problem. Is there a feature for this?Sansbury
The IDE (IntelliJ) stored the changes locally which saved the day. Thanks for the tip!Weldonwelfare
PHPStorm 2017.2: right click in editor -> Local History -> Show History. But now that I almost had to learn the hard way, I think I'll follow @JanHudec's suggestion of favouring alternatives over git reset whenever possible.Faruq
I just got saved by PhpStorm's local historyGaither
git reset HEAD@{1} caused an error in powershell terminal resulting error: unknown switch ``e' The way around this is escaping the curly braces with single quotes like this: git reset 'HEAD@{1}' because curlies have a different meaning for powershellCrematory
re vim and eclipse: great suggestion. i have personally used both vim and eclipse to recover old code that was not in git repo. eclipse is especially useful with it's local history feature b/c i think it updates every save you do.Josephjosepha
As a note, git log HEAD@{1} will also show the lost commits, to review before you reset to them.Noshow
Indeed local history in Eclipse (Intellij in my case) save my day in recovering unstrage changes, doc here for Intellij : blog.jetbrains.com/idea/2008/01/…Revitalize
Just to complete the git show -- cd .git/lost-found/commit; ls; git show abc123... > ~/rescue.patch, then work through the patch using git apply.Thromboplastic
So in lost-found I got a single file other\SOME_HASH. Turns out it is a git tree. I could see its contents running git ls-tree -r SOME_HASH. And restore all the files from it (requires git 2.23, restore command is new) with git restore -s SOME_HASH -W -S .Ashly
After code a half day, I decide to git add . and then I suddenly do a git reset --hard HEAD, and then I do git status, I found nothing, My GOD. you give me second chance to live in the world :)Complimentary
Shell snippet to review any files that were added to the staging area but never committed: for fname in $(ls .git/lost-found/other/); do echo $fname:; cat .git/lost-found/other/$fname; read -n 1 -p "Continue?"; echo; doneNabataean
For VSCode there is Timeline tab in the explorer, where you can see previous versions of your file , hope it will help someoneGittel
On all JetBrains IDE (Webstorm, IntelliJ, etc...), a simple ctrl+z will show a prompt asking if you want to reload the file from the disk and its cache. Doing so will restore all the changes on that file from the cache. Thanks!Vesuvius
For those files which doesn't exist now: create the same file at the same path and then call its Local historyExperience
B
782

For previously committed changes (answer from this SO):

$ git reflog show

4b6cf8e (HEAD -> master, origin/master, origin/HEAD) HEAD@{0}: reset: moving to origin/master
295f07d HEAD@{1}: pull: Merge made by the 'recursive' strategy.
7c49ec7 HEAD@{2}: commit: restore dependencies to the User model
fa57f59 HEAD@{3}: commit: restore dependencies to the Profile model
3431936 HEAD@{4}: commit (amend): restore admin
033f5c0 HEAD@{5}: commit: restore admin
ecd2c1d HEAD@{6}: commit: re-enable settings app

# assuming you want to get back to 7c49ec7 (restore dependencies to the User model)

$ git reset HEAD@{2}
Bung answered 16/6, 2014 at 2:51 Comment(13)
Just to add to this answer this would help people who actually had committed changes that were thrown away via hard reset.Putrid
Great - but in my case the files were gone completely. Using git checkout HEAD@{19} allowed me to check out the lost files in a detached state. Then used git checkout -b new-branch-name to add them back to the repo in "attached" state.Nide
@NightOwl888: Git newbie here and I had the same problem that my files were still gone. Could you explain in more detail how you have recovered your files into an "attached" state (or could you explain what that actually means)? Thank you so much!Platinum
@user3385759 - In Git, when you use the checkout command on anything that is not a branch, it will go into a special "detached head" mode. This means you are not actually pointing at a branch, but you can view what was checked in at the state of the entity (in this case a reflog entry). From that state, you can turn it into a "real" branch that you can go back to again by using git checkout -b new-branch-name. The book Pragmatic Version Control Using Git is good at explaining Git in simple terms.Nide
@Bung can you explain the syntax of git reset HEAD@{2} please?Echolalia
ken and @Nide you guys just saved three days of my life! Wish you happiness and prosperity!Bridwell
@TimRandall HEAD@{2} actually kept the commit HEAD of 7c49ec7 (restore dependencies to the User model). So we make the assumption that was the commit accidentally thrown away and you want to get it back. This can be done via git reset HEAD@{2}Bung
This answers #34520165Hedi
This answer seems to be incorrect. The OP asked if it was possible to recover uncommitted changes. This only recovers committed changes that are orphaned.Osmen
Although this comment for committed changes but it saved my one days work. thanks...Perpend
this did not work for me. what worked was git reset --hard <commit-id-retrieved-using-reflog>Dennis
@DaniiarAbdiev Same for me... save 3 days of hard intensive work. A big thank to the authorKennakennan
In my case, @NightOwl888's answer didn't help to restore uncommitted changesExperience
D
631

You cannot get back uncommitted changes in general.

Previously staged changes (git add) should be recoverable from index objects, so if you did, use git fsck --lost-found to locate the objects related to it. (This writes the objects to the .git/lost-found/ directory; from there you can use git show <filename> to see the contents of each file.)

If not, the answer here would be: look at your backup. Perhaps your editor/IDE stores temp copies under /tmp or C:\TEMP and things like that.[1]

git reset HEAD@{1}

This will restore to the previous HEAD

[1] vim e.g. optionally stores persistent undo, eclipse IDE stores local history; such features might save your a**

Dennison answered 26/4, 2011 at 8:55 Comment(18)
Eclipse's local history - and in addition, since some changes were older than 6 days, my Time Machine backup of Eclipse's local history! For some reason the Time Machine backup of the folder managed by git did not contain my previous changes.Reiner
Here is the link for instructions as to how to recover files from Eclipse backup. wiki.eclipse.org/…Tanager
Luckily I have TimeMachine set up to backup every hour so I was able to scoop the files out of the last backup. It doesn't recover hidden files so far as I can tell so you should copy the files over directly from the filesystem.Maintenance
It doesn't make sense why git can't just backup uncommitted changes during a reset, even temporarily. This is an entirely preventable problem. Is there a feature for this?Sansbury
The IDE (IntelliJ) stored the changes locally which saved the day. Thanks for the tip!Weldonwelfare
PHPStorm 2017.2: right click in editor -> Local History -> Show History. But now that I almost had to learn the hard way, I think I'll follow @JanHudec's suggestion of favouring alternatives over git reset whenever possible.Faruq
I just got saved by PhpStorm's local historyGaither
git reset HEAD@{1} caused an error in powershell terminal resulting error: unknown switch ``e' The way around this is escaping the curly braces with single quotes like this: git reset 'HEAD@{1}' because curlies have a different meaning for powershellCrematory
re vim and eclipse: great suggestion. i have personally used both vim and eclipse to recover old code that was not in git repo. eclipse is especially useful with it's local history feature b/c i think it updates every save you do.Josephjosepha
As a note, git log HEAD@{1} will also show the lost commits, to review before you reset to them.Noshow
Indeed local history in Eclipse (Intellij in my case) save my day in recovering unstrage changes, doc here for Intellij : blog.jetbrains.com/idea/2008/01/…Revitalize
Just to complete the git show -- cd .git/lost-found/commit; ls; git show abc123... > ~/rescue.patch, then work through the patch using git apply.Thromboplastic
So in lost-found I got a single file other\SOME_HASH. Turns out it is a git tree. I could see its contents running git ls-tree -r SOME_HASH. And restore all the files from it (requires git 2.23, restore command is new) with git restore -s SOME_HASH -W -S .Ashly
After code a half day, I decide to git add . and then I suddenly do a git reset --hard HEAD, and then I do git status, I found nothing, My GOD. you give me second chance to live in the world :)Complimentary
Shell snippet to review any files that were added to the staging area but never committed: for fname in $(ls .git/lost-found/other/); do echo $fname:; cat .git/lost-found/other/$fname; read -n 1 -p "Continue?"; echo; doneNabataean
For VSCode there is Timeline tab in the explorer, where you can see previous versions of your file , hope it will help someoneGittel
On all JetBrains IDE (Webstorm, IntelliJ, etc...), a simple ctrl+z will show a prompt asking if you want to reload the file from the disk and its cache. Doing so will restore all the changes on that file from the cache. Thanks!Vesuvius
For those files which doesn't exist now: create the same file at the same path and then call its Local historyExperience
U
369

I accidentally ran git reset --hard on my repo today too while having uncommitted changes too today. To get it back, I ran git fsck --lost-found, which wrote all unreferenced blobs to <path to repo>/.git/lost-found/. Since the files were uncommitted, I found them in the other directory within the <path to repo>/.git/lost-found/. From there, I can see the uncommitted files using git show <filename>, copy out the blobs, and rename them.

Note: This only works if you added the files you want to save to the index (using git add .). If the files weren't in the index, they are lost.

Unavoidable answered 21/7, 2011 at 17:16 Comment(2)
I got just files with commit references in lost-found. But I could then do git show to get contents.Sickener
Just to save anyone time #!/bin/bash cd PATH_TO_PROJECT/.git/lost-found/other FILES=* COUNTER = 0 for f in $FILES do echo "Processing $f file..." git show $f > "PATH_TO_RECOVERY_DIRECTORY/$COUNTER.m" let COUNTER=COUNTER+1 doneMathematics
C
325

No not uncommitted changes but you can recover previously committed changes after a hard reset in git.

Use:

git reflog

to get the identifier of your commit. Then use:

git reset --hard <commit-id-retrieved-using-reflog>

This trick saved my life a couple of times.

You can find the documentation of reflog HERE.

Connate answered 2/12, 2016 at 19:20 Comment(5)
So far, I think this is the best and most concise answer. It may seem counter intuitive to recover from git reset --hard using another git reset --hard but if you don't use the --hard switch, you'll be left with entries in your workspace that would effectively revert the work you just recovered.Eudemonia
This answer is not correct. This approach only recovers previously committed changes. It will not be able to restore uncommitted changes (which is what this question is about).Charity
That's why the accepted answer starts with "You cannot get back uncommitted changes in general". I thought this might still be useful to some though. :)Connate
Perhaps then specify in the answer that this recovers only committed changes!Lowland
This is super useful for those who committed and then hard reset erroneously. Thank you so much, you saved my past 3 hours of cpp debugging workErrolerroll
W
84

While I was working on a local project, I wanted to move it to GitHub and then created a new repository. While I was trying to add all these files to the new repository with .gitignore, I accidentally added a wrong file and then tried to clear it.

I ran git reset --hard origin/master

Then all of my local files deleted because the repo was empty. I thought everything was gone.

This worked for me:

git reflog show
git reset HEAD@{1} 
git push 
Whichever answered 6/11, 2016 at 16:3 Comment(0)
D
65

If you use something like IntelliJ:

On the context menu, choose Local History, and click Show History on the submenu:

The local history view for a project or folder shows you everything that you have done during the last few days. In the Action column of the lower part of the dialog box, select the action you want to roll back. [...] So doing, the upper part of the dialog box shows the tree view of changed files. If you want to restore the deleted file only, regardless of the other changes that have been done since then, you can select the file Lost.txt in the tree view and click the Revert button.

http://blog.jetbrains.com/idea/2008/01/using-local-history-to-restore-deleted-files/

Delgado answered 29/5, 2015 at 8:19 Comment(1)
This is by far the best answer for IntelliJ users! Thank you so much, this worked perfectly. I tried every other solution and none of them worked well. git reflog didn't work because I didn't commit the changes. git fsck --lost-found worked for staged files but not all of them were staged. IntelliJ's Local History perfectly recovered my unsaved files, I'm so grateful for this featureGlorify
L
48

I just did git reset --hard and lost all my uncommitted changes. Luckily, I use an editor (IntelliJ) and I was able to recover the changes from the Local History. Eclipse should allow you to do the same.

Lied answered 13/1, 2012 at 14:8 Comment(1)
Same thing applied for me in Visual Studio Code. There is a Timeline feature that proved really helpful in this scenario.Neap
N
23

By definition, git reset --hard will throw away uncommitted changes without any way for Git to recover them (your backup system may help, but not Git).

Actually, there are very few cases where git reset --hard is a good idea. In most cases, there's a safer command to do the same thing:

  • If you want to throw away your uncommitted changes, then use git stash. It will keep a backup of these changes, which will expire after some time if you run git gc. If you're 99.9% sure you'll never need these changes back, then git stash is still your friend for the 0.1% case. If you're 100% sure, then git stash is still your friend because these 100% have a measurement error ;-).

  • If you want to move your HEAD and the tip of the current branch in history, then git reset --keep is your friend. It will do the same thing as git reset --hard, but will not discard your local changes.

  • If you want to do both, then git stash && git reset --keep is your friend.

Teach your fingers not to use git reset --hard, it will pay back one day.

Nino answered 29/5, 2015 at 9:55 Comment(3)
so if one does git stash && git reset --hard that would wipe out any stashed content is that right?Joubert
No, git reset --hard doesn't discard the stash. git stash is a replacement for git reset --hard in the sense that it removes uncommited changes from your worktree, except that it keeps them safe instead of discarding them permanently.Nino
or just commit your changes before you reset hard and they will still be in your local repoDesigned
B
15

This is what I usually do if I lose some changes.

git reflog
git checkout <commit id> // now you are in where you want but you cannot push from detached branch to master
manually copy and paste changes from detached branch to master or working branch
git reset --hard HEAD // if needed
git add ... > git commit ... > git push ...

to move the pointer back to your previous commits but keeping the changes you made so far in your latest commits checkout git reset --soft dadada

Braunstein answered 30/5, 2017 at 23:27 Comment(0)
B
14

IntelliJ has a temporary folder accessible through the history command:

  1. Select the folder to revert files from in your navigation pane
  2. Double tap the Shift key (shift-shift)
  3. In the input box that pops up type Local History and press Enter
  4. Select Show History
  5. Now you can revert to the version you need.
Bramblett answered 2/6, 2021 at 6:55 Comment(0)
C
13

I ran into same issue and I was almost going insane....initially I committed the project and merged. Later when I try running git push --set-upstream origin master I was getting this error

  fatal: refusing to merge unrelated histories

so I ran git reset --hard HEAD and it deleted a 3 weeks project but these few commands below save the day:

git reset HEAD@{1}         //this command unstage changes after reset
git fsck --lost-found      //I got the dangling commit fc3b6bee2bca5d8a7e16b6adaca6a76e620eca4b
git show <dangling commit something like-> fc3b6bee2bca5d8a7e16b6adaca6a76e620eca4b>
git rebase fc3b6bee2bca5d8a7e16b6adaca6a76e620eca4b
Chiseler answered 28/1, 2019 at 19:28 Comment(0)
M
11

The information is lost.

Since you did not commit, your .git never stored this information. So, basically git cannot recover it for you.

But, If you just did git diff, there is a way you can recover using the terminal output with the following 3 simple steps.

  1. scroll your terminal and look for the o/p of git diff. Save the o/p in a file called diff.patch
  2. Search & Replace all 7 spaces and 8 spaces with tab(\t) character and save the changes.
  3. Go into your git repository. Apply the diff.patch (patch -p1 < diff.patch)

Note: While you are copying the data from terminal to a file, be careful and clearly see that the data is continuous output and did not contain any redundant data(due to pressing up and down arrows). Otherwise you might mess it up.

Marchak answered 1/8, 2014 at 7:17 Comment(0)
C
7

If you luckily had the same files opened on another editor (eg. Sublime Text) try a ctrl-z on those. It just saved me..

Connate answered 17/2, 2016 at 11:59 Comment(0)
Z
4

I found out the hard way that any uncommitted files before a git reset --hard <commit> gets removed from git history. However, I was lucky enough to have kept my code editor session open during the entire time I was pulling my hair out, that I discovered that a simple control + z in each of the affected files returned the state of the file back to the version before Git so obligingly reset everything I didn't ask it to specifically. Hooray!!

Zero answered 6/9, 2017 at 5:28 Comment(0)
K
3

If you're on (any recent) macOS, and even if you're away from your Time Machine disk, the OS will have saved hourly backups, called local snapshots.

Enter Time Machine and navigate to the file you lost. The OS will then ask you:

The location to which you're restoring "file.ext" already contains an
item with the same name. Do you want to replace it with the one you're
restoring?

You should be able to recover the file(s) you lost.

Kooima answered 3/10, 2019 at 21:57 Comment(2)
On MacOS/VSCode, you could simply drag them back if you have not emptied your trash.Enslave
@QiangLi Yes, sure, but the point here is that you may have edited the file and removed material that you subsequently needed, but you had saved in the interim.Kooima
S
2

Here is the way that worked for me in IntellijIDEA when I did a hard reset and had uncommited changes:

  1. Right-click to select the package in which you want to restore file.
  2. Choose Local History -> Show History.
  3. Select a change and revert or create a patch.
Serious answered 19/4, 2023 at 8:47 Comment(0)
S
1

For VSCode users whom lost unstaged & uncommitted changes

This will only work if you didn’t extensively edit your files again after reset.

tl;dr Try undoing the file changes in VSCode

I did git reset —-hard when my stakeholders decided to de-scope a feature while I was building it. The same stakeholders changed their minds an hour later.

I took a break and came back. After I saw they changed their minds, I then decided to try and undo the files I was working on and it worked! I managed to get back all my work.

Slier answered 10/6, 2022 at 18:47 Comment(3)
For VSCode there is Timeline tab in the file explorer, where you can see previous versions of your file, it helped meGittel
Thanks for your comment! Ctrl+Z was not working for me. TImeline saved my work!Kolnos
@Gittel you've a lifesaver!Bluestone
C
1

I encountered a scenario where I checked out my local changes without committing or stashing them. No command could help me, as much as I know. The thing that worked for me was CTRL+Z.

CTRL + Z

By chance all of my file were open in editor so in the editor I just press CTRL+Z on required files, this solved my problem

PS: I was using Sublime text editor.

Cuisine answered 31/8, 2022 at 8:11 Comment(1)
not sure why was this downvoted. CTRL + Z did help to recover my uncommitted changesCandelaria
T
0

If you're developing on Netbeans, look between the file tabs and the file edit area. There is a "Source" and "History". On "History" you'll see changes made using version control (git/other), but also changes made locally. In this case, local changes could save you.

Thrombophlebitis answered 20/5, 2018 at 21:16 Comment(0)
L
0

You can only recover staged (git add) changes that you have lost.

you can recover easily by running this command

step:1 Go to project root directory and then run this command

npx git-recover

step:2 enter recovery directory path like

/Users/apple/RecoveryDirectory

you will get lost file in RecoveryDirectory

enter image description here

Lamia answered 16/9, 2021 at 21:32 Comment(0)
A
0

Well, the best solution as far as i know is to use the IDE features.

  • select the repository where you lost the files and right click on it
  • find for Local history in menu > show history
  • Now check in version version you all files exist > select that and click on revert. That's all for most possible case.

NOTE: Above solution will work when you were doing change or having repository imported in any IDE eg intelliJ.

Aliquot answered 3/2, 2023 at 4:12 Comment(0)
O
0

If you don't want to do a hard reset, you can recover the lost commit as a new branch...

First:

git reflog

Find the commit you want to recover. It will likely be right at the top if you just made the commit before losing it. Though you may need to scroll further down to find it (press Enter or PageDown). Take note of the HEAD number, and replace 57:

git checkout HEAD@{57}

Create a new branch with the recovered commit:

git checkout -b recovery_branch

You could then cherry pick the commit into your dev branch or do whatever you like with it.

Obscuration answered 1/4, 2023 at 23:13 Comment(0)
A
-1

For later you can use VSCode with ext: GitLens - Git supercharged so you can reverse your code with this extensions

Acceptor answered 19/5, 2021 at 4:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.