Git: checking out a file from a previous commit and amending it to HEAD

前端 未结 2 369
清歌不尽
清歌不尽 2021-01-30 15:47

I recently committed a file to the HEAD of my branch which has errors in it. I need to do the following things:

  • Get that file from one commit previous to HEAD <
相关标签:
2条回答
  • 2021-01-30 16:24

    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'
    
    0 讨论(0)
  • 2021-01-30 16:45

    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.

    0 讨论(0)
提交回复
热议问题