Last Updated: December 19, 2019
·
1.499K
· naiquevin

Recovering files deleted in a previous git commit

Let's say you deleted one or more files in a previous git commit but now you need to recover them. First find out the specific commit that deleted the files and then use this one-liner to get them all back

$ git show --name-status COMMIT_HASH | grep -P "^D\t" | sed "s/D\t//" | xargs -n 1 git checkout COMMIT_HASH~1

Note that the hash of the commit which deleted the files must go in place of COMMIT_HASH in the above command.

What's happening?

  • git show along with --name-status will list all files that were involved in the commit along with their status
  • Using grep get only the deleted files (having 'D' as the status)
  • Using sed get rid of extra output keeping only the path of the files
  • Using xargs checkout all filepaths from the previous git commit (COMMIT_HASH~1) in one go

2 Responses
Add your response

There is always git reflog

over 1 year ago ·

Would this be the correct operation/flow if you are "reverting" previous commited changes, as deleting a bunch of files?; before got to this post I was (and still) very confused on how to perform the operation whether using git revert, git restore, git reset, or git checkout. Anyhow, after executing this awesome line of code it's supposed that I have to commit the "new (added) files", right?

over 1 year ago ·