How would I extract a single file (or changes to a file) from a git stash?

Issue

I’d like to know if it is possible to extract a single file or diff of a file from a git stash without popping the stash changeset off.

Might anyone be able to provide some suggestions/ideas about this?

Solution

On the git stash manpage you can read (in the “Discussion” section, just after “Options” description) that:

A stash is represented as a commit whose tree records the state of the
working directory, and its first parent is the commit at HEAD when the
stash was created.

So you can treat stash (e.g. [email protected]{0} is first / topmost stash) as a merge commit, and use:

$ git diff [email protected]{0}^1 [email protected]{0} -- <filename>

Explanation: [email protected]{0}^1 means the first parent of the given stash, which as stated in the explanation above is the commit at which changes were stashed away. We use this form of “git diff” (with two commits) because [email protected]{0} / refs/stash is a merge commit, and we have to tell git which parent we want to diff against. More cryptic:

$ git diff [email protected]{0}^! -- <filename>

should also work (see git rev-parse manpage for explanation of rev^! syntax, in “Specifying ranges” section).

Likewise, you can use git checkout to check a single file out of the stash:

$ git checkout [email protected]{0} -- <filename>

or to save it under another filename:

$ git show [email protected]{0}:<full filename>  >  <newfile>

or

$ git show [email protected]{0}:./<relative filename> > <newfile>

(note that here <full filename> is full pathname of a file relative to top directory of a project (think: relative to [email protected]{0})).


You might need to protect [email protected]{0} from shell expansion, i.e. use "[email protected]{0}" or '[email protected]{0}'.

Answered By – Jakub NarÄ™bski

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published