Git stash: "Cannot apply to a dirty working tree, please stage your changes"

avernet picture avernet · Sep 1, 2009 · Viewed 51.9k times · Source

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?

Answer

muhqu picture muhqu · Sep 17, 2010

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.