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

前端 未结 2 370
清歌不尽
清歌不尽 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  path/to/file.ext
    git commit -m 'Revert this file to real previous commit'
    

提交回复
热议问题