Search code examples
gitgit-stash

stuck with stash in git


I am using git, but have alot to learn. I wanted to save some changes to a file (but not commit) and go to a different branch, have a look at some code there then go back to what I was working on. That's all. So I did

> git stash
> git checkout
> vi ....
> git stash apply stash@{0}

and found myself facing an error message

Auto-merging schematic.f
CONFLICT (content): Merge conflict in schematic.f

I obviously didn't realize how stash apply was going to work. And now I'm stuck. Nothing I can think of doing will get me out of my current branch and back to the one I was working in. I keep getting this same error message over and over. How do I get out of this? Thanks.


Solution

  • Fortunately, apply means try out the stash in my current work-tree, but keep the stash so the stash itself is fully intact.1 And, based on your command sequence (and assuming vi ... was just to look at something, not change it), your stash then checkout should have left you a clean work-tree at the now-current commit, so all you have to do is force the work-tree to match the current commit, with:

    git reset --hard HEAD
    

    (note that git reset --hard wipes away any changes made to the work-tree so be sure that all the changes there are just ones made by git stash apply: you might want to check git status and git diff first, for instance, just to be doubly and triply sure).

    Once the work-tree is clean again, you can git checkout the branch you do want the changes on, git stash apply the stash, and if all goes well, git stash drop it.


    1I always recommend git stash apply instead of git stash pop for this reason, although in fact, pop only drops the stash if it applies cleanly, so the distinction is pretty small.