97

Possible Duplicate:
How to revert a “git rm -r .”?

Git SOS here. I worked 10 hours on a project without committing (I know, I know) and then I git added too many files, so I tried using git rm and accidentally deleted EVERYTHING. Is there hope for me? :(((

Community
  • 1
  • 1
user1436111
  • 2,111
  • 7
  • 24
  • 41

1 Answers1

183

If you already commited changes, then:

git reset (--hard) HEAD~1

If not then:

git reset
git ls-files -d -z | xargs -0 git checkout --
Hauleth
  • 22,873
  • 4
  • 61
  • 112
  • 4
    Would `git reset --hard HEAD` work in the second case? – Tamás Szelei Apr 30 '13 at 11:02
  • 9
    Will, but it will also discard all your changes. – Hauleth Apr 30 '13 at 12:47
  • Ah, ok. What exactly is the second line doing here? Is it strictly undoing the rm, or does it have a wider effect? – Tamás Szelei Apr 30 '13 at 14:19
  • It remove all files in index and then checkout all modified files to HEAD. – Hauleth Apr 30 '13 at 22:18
  • Be careful when using the second one, I tried using it to recover some accidentally rm'd files and lost my uncommitted changes. Noob mistake I guess. – Craig Brett Aug 26 '14 at 09:36
  • 1
    To restore deleted files the last part should look like `git ls-files -d` and thet it will recover only deleted files. – Hauleth Aug 26 '14 at 09:38
  • I lost all my uncommited changes after `git checkout -- $(git ls-files -m)`. I don't know if what other people are commenting here is right (using `git ls-files -d` instead), but someone who knows should edit this answer – Carles Jove i Buxeda Jan 30 '15 at 10:34
  • `git checkout -- $(git ls-files -d)` This doesn't work if the filenames have spaces in them – Chris P Jul 17 '15 at 02:01
  • 2
    `git ls-files -d -z | xargs -0 git checkout --` is the way to go for the generic case with filename spaces (http://jennyandlih.com/using-git-ls-files-input-xargs) – Chris P Jul 17 '15 at 02:31
  • install trash and then `alias rm=trash` in `.zshrc` or similar, now all deletes are undo able :) – timeyyy Jun 29 '16 at 20:43
  • Is `xargs` only for linux? How can I do the same thing from the Windows command line? – Arthur Aug 25 '21 at 11:49