I recently committed a file to the HEAD of my branch which has errors in it. I need to do the following things:
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.
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'
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 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
.