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

查看:266
本文介绍了如何在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, this 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天全站免登陆