从 git 中的旧提交恢复文件
我有一个几周前做的旧承诺。我只想从该提交中恢复一个文件。我该怎么办?
I have an old commit that I did a few weeks ago. I want to restore only a single file from that commit. What do I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不会改变 HEAD,它只会覆盖本地文件
path/to/file.txt
请参阅 man git-rev-parse 获取可能的修订规范(当然,一个简单的散列(如
dd9bacb
)就可以了)不要忘记提交更改(在 审查...)
This will not alter HEAD, it will just overwrite the local file
path/to/file.txt
See man git-rev-parse for possible revision specifications there (of course a simple hash (like
dd9bacb
) will do nicely)Don't forget to commit the change (after a review...)
git checkout [Revision_Key] -- path/to/file
.所有答案都提到 git checkout-- <路径规范>。从 git v2.23.0 开始,有一个新的 git Restore 方法,该方法被认为是承担 git checkout 负责的部分内容。请在 github 博客上查看变更要点。
此命令的默认行为是使用来自
source
参数(在您的情况下将是提交哈希)的内容恢复工作树的状态。假设提交哈希是abcdef,命令将如下所示:(
默认情况下)将其放入工作树中。如果您想将更改直接放入索引中,以便可以立即提交:
或使用简短的选项名称:
All answers mention
git checkout <tree-ish> -- <pathspec>
. As of git v2.23.0 there's a new git restore method which is supposed to assume part of whatgit checkout
was responsible for. See highlights of changes on github blog.The default behaviour of this command is to restore the state of a working tree with the content coming from the
source
parameter (which in your case will be a commit hash).Assuming the commit hash is
abcdef
the command would look like this:which (by default) puts it in working tree. If you want to put the change directly in index so it can be committed straight away:
or with short option names:
我需要恢复最近提交到 git 的文件。
因此,为了重申并提供另一个视角,您需要通过运行以下两个步骤来完成此操作:
git log -3
这显示了最近的三个提交。阅读评论和作者姓名,以便缩小您想要的确切版本的范围。
记下您想要的提交版本的长提交 ID(例如
b6b94f2c19c456336d60b9409fb1e373036d3d71
)。git checkout b6b94f2c19c456336d60b9409fb1e373036d3d71 -- myfile.java
传递提交 ID 和要恢复的文件名。确保双连字符前后都有空格。
还有很多其他方法可以做到这一点,但这是我记得的最简单的一种。
注意:如果您位于项目路径/文件夹内,则无需在结帐命令中键入完整文件的路径。
I needed to restore a recent file committed into git.
So just to reiterate and give another perspective, you need to do this by running the following two steps:
git log -3
This shows the three most recent commits. Read the comments and the author's name so you narrow down what exact version you want.
Write down that long commit ID (e.g.
b6b94f2c19c456336d60b9409fb1e373036d3d71
) for the commit version you want.git checkout b6b94f2c19c456336d60b9409fb1e373036d3d71 -- myfile.java
Pass the commit ID AND the file name you want to restore. Make sure you have a space before and after the double hyphen.
There are many other ways to do it but this is the simplest one I can remember.
NOTE: If you are inside your project path/folder then is not necessary to type the full file's path in the checkout command.