如何在 Git 存储库中查找和恢复已删除的文件 [英] How to find and restore a deleted file in a Git repository

查看:61
本文介绍了如何在 Git 存储库中查找和恢复已删除的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Git 存储库中.我删除了一个文件并提交了该更改.我继续工作并做出更多承诺.然后,我发现我需要恢复那个文件.

Say I'm in a Git repository. I delete a file and commit that change. I continue working and make some more commits. Then, I find I need to restore that file.

我知道我可以使用 git checkout HEAD^ foo.bar 检出文件,但我真的不知道该文件何时被删除.

I know I can checkout a file using git checkout HEAD^ foo.bar, but I don't really know when that file was deleted.

  1. 找到删除给定文件名的提交的最快方法是什么?
  2. 将文件恢复到我的工作副本的最简单方法是什么?

我希望我不必手动浏览我的日志,检查给定 SHA 的整个项目,然后手动将该文件复制到我的原始项目检查中.

I'm hoping I don't have to manually browse my logs, checkout the entire project for a given SHA and then manually copy that file into my original project checkout.

推荐答案

查找影响给定路径的最后一次提交.由于该文件不在 HEAD 提交中,因此之前的提交肯定已将其删除.

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>

然后在提交之前检查版本,使用插入符号 (^) 符号:

Then checkout the version at the commit before, using the caret (^) symbol:

git checkout <deleting_commit>^ -- <file_path>

或者在一个命令中,如果 $file 是相关文件.

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

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


如果您正在使用 zsh 并启用了 EXTENDED_GLOB 选项,则插入符号将不起作用.您可以使用 ~1 代替.

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

这篇关于如何在 Git 存储库中查找和恢复已删除的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆