[英]Git: checking out a file from a previous commit and amending it to HEAD
I recently committed a file to the HEAD of my branch which has errors in it. 我最近向我的分支机构的HEAD提交了一个文件,其中有错误。 I need to do the following things: 我需要做以下事情:
What's the best way of going about that? 最好的方法是什么?
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
开关将其--amend
到上git-commit
。
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. Git checkout HEAD~1(或HEAD ^)index.php尝试将index.php文件签出到先前的HEAD哈希(bbbbbbb),但这不是真正的先前提交哈希文件,是ccccccc。 In the previous HEAD hash, index.php still remain unchanged because the last changed was made in hash 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.