Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo git checkout overwrite of uncommitted files

I had used the command git checkout -- $(git ls-files -m) to undo a git rm on some files. However, I had modified some other files without committing them, and these files have been reverted to their previous commit, losing the uncommitted changes.

Is there a way to get these changes back?
I imagine not with git as the changes weren't added to git. On a Mac if that helps.

Thanks Tom

like image 957
holmeswatson Avatar asked Apr 09 '14 10:04

holmeswatson


People also ask

Is it possible to undo git checkout --?

No, you can't recover from this with Git, unless maybe you used git stash at some point or you created lots of new files, staged, and unstaged them (unlikely). Commit more often and set up backups in the future.

How do I undo a staged change in git?

Staged files are those which go into your next commit. If you accidentally added files to the staged area, you can undo this by typing git restore --staged <file> , so in this case, it would be git restore --staged lib.

How do I revert a modified file in git?

If you have modified, added and committed changes to a file, and want to undo those changes, then you can again use git reset HEAD~ to undo your commit. Similar to the previous example, when you use git reset the modifications will be unstaged.


2 Answers

By default you can't get it back, but you may be lucky in such an emergency situation and be able to retrieve a file that you accidentally clobbered by git checkout filename in the following ways:

  • You may still have the file buffered in a text editor (for me I have found in my BBEdit text editor that, if I had it open, I can do an
    undo to get the file back (because it tends to be loaded to the
    current version if the file on disk is changed), and then save.
  • Also if you have continuous backup running you might also be able to get back a version you edited. For example Apple Time Machine might
    have a version from only a short while ago.
like image 127
Timothy C. Lethbridge Avatar answered Sep 28 '22 01:09

Timothy C. Lethbridge


"Does git checkout really silently overwrite uncommitted changes?"
And the answer is still "yes" in 2018 (just tested with 2.11)

It is true in August 2019, with Git 2.23, except there is now a more explicit git restore command

A simple git restore . would also restore the working tree silently, from the index content (so if the files were modified but not added to said index, their changes would still be lost)

But at least there is no confusion possible between checkout of files and of branch.

like image 38
VonC Avatar answered Sep 28 '22 02:09

VonC