How to find and restore a deleted file in a Git repository

Explanation

To find and restore a deleted file in a Git repository we have to find the last commit that affected the given path. As the file isn’t in the HEAD commit, that previous commit must have deleted it.

git rev-list -n 1 HEAD -- <file_path>

 And before using the caret (^) symbol, we have to check the version at the commit :

git checkout <deleting_commit>^ -- <file_path>

  Or if there is one command, then the $file is the file in question.

git checkout $(git rev-list -n 1 HEAD -- "$file")^ -- "$file"
git checkout $(git rev-list -n 1 HEAD -- "$file")~1 -- "$file"

 

Also read, How to concatenate string variables in Bash

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *