How to retrieve a single file from a specific revision in Git?

后端 未结 10 1399
臣服心动
臣服心动 2020-11-22 15:50

I have a Git repository and I\'d like to see how some files looked a few months ago. I found the revision at that date; it\'s 27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8<

10条回答
  •  借酒劲吻你
    2020-11-22 16:05

    In addition to all the options listed by other answers, you can use git reset with the Git object (hash, branch, HEAD~x, tag, ...) of interest and the path of your file:

    git reset  /path/to/file
    

    In your example:

    git reset 27cf8e8 my_file.txt
    

    What this does is that it will revert my_file.txt to its version at the commit 27cf8e8 in the index while leaving it untouched (so in its current version) in the working directory.

    From there, things are very easy:

    • you can compare the two versions of your file with git diff --cached my_file.txt
    • you can get rid of the old version of the file with git restore --staged file.txt (or, prior to Git v2.23, git reset file.txt) if you decide that you don't like it
    • you can restore the old version with git commit -m "Restore version of file.txt from 27cf8e8" and git restore file.txt (or, prior to Git v2.23, git checkout -- file.txt)
    • you can add updates from the old to the new version only for some hunks by running git add -p file.txt (then git commit and git restore file.txt).

    Lastly, you can even interactively pick and choose which hunk(s) to reset in the very first step if you run:

    git reset -p 27cf8e8 my_file.txt
    

    So git reset with a path gives you lots of flexibility to retrieve a specific version of a file to compare with its currently checked-out version and, if you choose to do so, to revert fully or only for some hunks to that version.


    Edit: I just realized that I am not answering your question since what you wanted wasn't a diff or an easy way to retrieve part or all of the old version but simply to cat that version.

    Of course, you can still do that after resetting the file with:

    git show :file.txt
    

    to output to standard output or

    git show :file.txt > file_at_27cf8e8.txt
    

    But if this was all you wanted, running git show directly with git show 27cf8e8:file.txt as others suggested is of course much more direct.

    I am going to leave this answer though because running git show directly allows you to get that old version instantly, but if you want to do something with it, it isn't nearly as convenient to do so from there as it is if you reset that version in the index.

提交回复
热议问题