Git stash: “Cannot apply to a dirty working tree,

2019-01-20 21:41发布

I am trying to apply changes I stashed earlier with git stash pop and get the message:

Cannot apply to a dirty working tree, please stage your changes

Any suggestion on how to deal with that?

标签: git git-stash
11条回答
倾城 Initia
2楼-- · 2019-01-20 21:44

I was unable to get most of these to work; for some reason it always thinks I have local changes to a file. I can't apply a stash, patches won't apply, checkout and reset --hard fail. What finally worked was saving the stash as a branch with git stash branch tempbranchname, and then doing a normal branch merge: git checkout master and git merge tempbranchname. From http://git-scm.com/book/en/Git-Tools-Stashing :

If you want an easier way to test the stashed changes again, you can run git stash branch, which creates a new branch for you, checks out the commit you were on when you stashed your work, reapplies your work there, and then drops the stash if it applies successfully

查看更多
淡お忘
3楼-- · 2019-01-20 21:46

I do it in this way:

git add -A
git stash apply

and then (optionaly):

git reset
查看更多
神经病院院长
4楼-- · 2019-01-20 21:47

When I have to apply stashed changes to a dirty working copy, e.g. pop more than one changeset from the stash, I use the following:

$ git stash show -p | git apply -3 && git stash drop

Basically it

  1. creates a patch
  2. pipes that to the apply command
  3. if there are any conflicts they will need to be resolved via 3-way merge
  4. if apply (or merge) succeeded it drops the just applied stash item...

I wonder why there is no -f (force) option for git stash pop which should exactly behave like the one-liner above.

In the meantime you might want to add this one-liner as a git alias:

$ git config --global --replace-all alias.unstash \
   '!git stash show -p | git apply -3 && git stash drop'
$ git unstash

Thanks to @SamHasler for pointing out the -3 parameter which allows to resolve conflicts directly via 3-way merge.

查看更多
你好瞎i
5楼-- · 2019-01-20 21:49

You have files that have been modified but not committed. Either:

git reset --hard HEAD (to bring everything back to HEAD)

or, if you want to save your changes:

git checkout -b new_branch
git add ...
git commit
git checkout -b old_branch
git stash pop
查看更多
我只想做你的唯一
6楼-- · 2019-01-20 21:53

You can apply a stash to a "dirty" tree by doing a git add to stage any changes you've made, thus cleaning up the tree. Then you can git stash pop and apply the stashed changes, no problem.

查看更多
相关推荐>>
7楼-- · 2019-01-20 21:54

None of these answers actually work if you find yourself in this situation as I did today. Regardless of how many git reset --hard's I did, it got me nowhere. My answer (not official by any means was):

  1. Figure out the stash's hash use git reflog --all
  2. Merge that hash with the branch you're interested in
查看更多
登录 后发表回答