Git - undoing git rm

78,449

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 --
Share:
78,449
user1436111
Author by

user1436111

Updated on October 15, 2020

Comments

  • user1436111
    user1436111 over 3 years

    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? :(((

  • Tamás Szelei
    Tamás Szelei almost 11 years
    Would git reset --hard HEAD work in the second case?
  • Hauleth
    Hauleth almost 11 years
    Will, but it will also discard all your changes.
  • Tamás Szelei
    Tamás Szelei almost 11 years
    Ah, ok. What exactly is the second line doing here? Is it strictly undoing the rm, or does it have a wider effect?
  • Hauleth
    Hauleth almost 11 years
    It remove all files in index and then checkout all modified files to HEAD.
  • Omar Wagih
    Omar Wagih over 10 years
    You're a freaking lifesaver!
  • Craig Brett
    Craig Brett over 9 years
    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.
  • Hauleth
    Hauleth over 9 years
    To restore deleted files the last part should look like git ls-files -d and thet it will recover only deleted files.
  • Carles Jove i Buxeda
    Carles Jove i Buxeda about 9 years
    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
  • Chris P
    Chris P almost 9 years
    git checkout -- $(git ls-files -d) This doesn't work if the filenames have spaces in them
  • Chris P
    Chris P almost 9 years
    git ls-files -d -z | xargs -0 git checkout -- is the way to go for the generic case with filename spaces (jennyandlih.com/using-git-ls-files-input-xargs)
  • timeyyy
    timeyyy almost 8 years
    install trash and then alias rm=trash in .zshrc or similar, now all deletes are undo able :)
  • lucasfcosta
    lucasfcosta almost 7 years
    You just saved my whole day of work. I learned a lesson today.
  • kaiser
    kaiser over 3 years
    I have never ever before been so much in love as with your lines above.
  • Arthur
    Arthur over 2 years
    Is xargs only for linux? How can I do the same thing from the Windows command line?