I stashed my changes. Now I want to unstash only some files from the stash. How can I do this?
If you git stash pop (with no conflicts) it will remove the stash after it is applied. But if you git stash apply it will apply the patch without removing it from the stash list. Then you can revert the unwanted changes with git checkout -- files...
To stash a specific file, use the “git stash push” command and specify the file you want to stash. However, the other tracked files that may be modified in your current working directory are untouched.
To pop a specific stash in git, you can use the git stash apply command followed by the stash@{NUMBER} command. command. It will show the list of stashes you have saved.
Git stashing single files is useful when you want to pick and choose which files to stash from you working directory changes. The Git Stash is a holding area for in progress changes that you want to preserve but need keep out of the way temporarily. For example, you may want to change branches.
As mentioned below, and detailed in "How would I extract a single file (or changes to a file) from a git stash?", you can apply use git checkout
or git show
to restore a specific file.
git checkout stash@{0} -- <filename>
With Git 2.23+ (August 2019), use git restore
, which replaces the confusing git checkout
command:
git restore --source='stash@{0}' -- <filename>
That does overwrite filename
: make sure you didn't have local modifications, or you might want to merge the stashed file instead.
(As commented by Jaime M., for certain shell like tcsh where you need to escape the special characters, the syntax would be: git checkout 'stash@{0}' -- <filename>
)
or to save it under another filename:
git show stash@{0}:<full filename> > <newfile>
(note that here
<full filename>
is full pathname of a file relative to top directory of a project (think: relative tostash@{0}
)).
yucer suggests in the comments:
If you want to select manually which changes you want to apply from that file:
git difftool stash@{0}..HEAD -- <filename>
Vivek adds in the comments:
Looks like "
git checkout stash@{0} -- <filename>
" restores the version of the file as of the time when the stash was performed -- it does NOT apply (just) the stashed changes for that file.
To do the latter:
git diff stash@{0}^1 stash@{0} -- <filename> | git apply
(as commented by peterflynn, you might need | git apply -p1
in some cases, removing one (p1
) leading slash from traditional diff paths)
As commented: "unstash" (git stash pop
), then:
git add
)git stash --keep-index
The last point is what allows you to keep some file while stashing others.
It is illustrated in "How to stash only one file out of multiple files that have changed".
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