David's Blog

TIL: Reading a file from a particular git commit

Use 'git show <rev>:<path>' to output a single file's contents from a particular revision. This can be redirected into a file or piped into other programs, etc.

Something I have occasionally wondered is whether git provides a way to read a single file from a particular commit/revision without checking out that commit (and thus changing the state of the whole working copy). It seemed like something git should support but in brief searches and man page readings, never found a way to do so.

Today, I finally read through the gitrevisions(7) manpage (referenced by git-show's) and saw the <rev>:<path> syntax:

<rev>:<path>, e.g. HEAD:README, master:./README

A suffix : followed by a path names the blob or tree at the given path in the tree-ish object named by the part before the colon. A path starting with ./ or ../ is relative to the current working directory. The given path

will be converted to be relative to the working tree’s root directory. This is most useful to address a blob or tree from a commit or tree that has the same tree structure as the working tree.

This seems to be exactly what I needed and it turns out git show supports this syntax for outputting a particular file!