Git:检出先前提交中的文件并将其修改为 HEAD
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/900560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Git: checking out a file from a previous commit and amending it to HEAD
提问by Coocoo4Cocoa
I recently committed a file to the HEAD of my branch which has errors in it. I need to do the following things:
我最近向我的分支的 HEAD 提交了一个文件,其中有错误。我需要做以下事情:
- Get that file from one commit previous to HEAD
- Commit that file back into HEAD
- 从 HEAD 之前的一次提交中获取该文件
- 将该文件提交回 HEAD
What's the best way of going about that?
最好的方法是什么?
回答by sykora
You've practically said it yourself:
你几乎自己说过:
First get the file back from one commit before:
首先从一次提交中取回文件:
$> git checkout HEAD~1 path/to/file.ext
Then commit it:
然后提交:
$> git commit -a -m 'Retrieved file from older revision'
If only the changes to that file where present in the last commit, you can even use git-revert
:
如果只有上次提交中存在对该文件的更改,您甚至可以使用git-revert
:
$> git revert HEAD
I think it would be better to make this a separate commit, because it tells you exactly what you've reverted, and why. However, you can squash this into the previous commit by using the --amend
switch to git-commit
.
我认为最好将其作为单独的提交,因为它会准确地告诉您已还原的内容以及原因。但是,您可以使用--amend
切换到git-commit
.
回答by Tecnocat
Be carefull, in this scenario:
小心,在这种情况下:
Commit hash - File modified
aaaaaaa index.php
bbbbbbb test.php
ccccccc index.php
Git checkout HEAD~1 (or HEAD^) index.php try to checkout the index.php file to previous HEAD hash (bbbbbbb) but this is not the real previous commit hash file, is ccccccc. In the previous HEAD hash, index.php still remain unchanged because the last changed was made in hash ccccccc.
Git checkout HEAD~1(或 HEAD^)index.php 尝试将 index.php 文件签出到之前的 HEAD 哈希(bbbbbbb),但这不是真正的之前提交的哈希文件,是 ccccccc。在之前的 HEAD 哈希中,index.php 仍然保持不变,因为最后一次更改是在哈希 ccccccc 中进行的。
To revert some file to previous commit hash that affected the file, use:
要将某个文件恢复到影响该文件的先前提交哈希,请使用:
git log -n 2 --pretty=format:%h path/to/file.ext
Ignore first hash and take the second hash, then:
忽略第一个散列并采用第二个散列,然后:
git checkout <second_hash> path/to/file.ext
git commit -m 'Revert this file to real previous commit'