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?
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.
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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With