Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I checkout an untracked file in a git stash?

Tags:

git

Assume I have stashed some changes using one of:

git stash -u
git stash --include-untracked

I can checkout an individual file from the stash via

git checkout stash@{0} -- filename

That works if git knows about "filename", but doesn't work if "filename" is untracked. Is there any way to checkout untracked files from a stash?

like image 822
eakst7 Avatar asked May 12 '14 12:05

eakst7


People also ask

How do I use untracked files in stash?

In order to stash untracked files, add the “–include-untracked” option to your “git stash” initial command. Alternatively, you can simply use the “-u” which is equivalent to the untracked longer version.

Can you git stash untracked files?

Another common thing you may want to do with stash is to stash the untracked files as well as the tracked ones. By default, git stash will stash only modified and staged tracked files. If you specify --include-untracked or -u , Git will include untracked files in the stash being created.

How do I remove untracked files from git stash?

Using git stash to delete files in a safer way Another method of getting a clean working directory is to use git stash to stash and delete both tracked and untracked files. You can do this using the --include-untracked command, which stashes all untracked files and then runs git clean behind the scenes for us.

Does git checkout remove untracked files?

git checkout does not affect untracked files. Git only manages tracked files, and it works fairly hard to avoid letting you lose data (which is critical).


1 Answers

git stash internally creates special black magic merge commits to store different parts of your changes. The merge commit has the original base commit (what you had at the top of the branch when you stashed) as its first parent, a throwaway commit representing the index contents at time of stashing as its second parent, and (only if you used --include-untracked) a throwaway commit containing the untracked files as its third parent.

So, the merge commit references the untracked files (as one of its parents)... but it doesn't actually include those files in its own tree (if that doesn't make any sense, either you've got a few things to learn yet about Git's internals... or you know too much about merge commits and this whole construct just seems too horrible to think about ;)).

In short... to access the untracked parts of your stash, access its third parent: git checkout stash@{0}^3 -- filename

like image 197
Jan Krüger Avatar answered Oct 17 '22 06:10

Jan Krüger