Reputation: 36671
I began making changes to my codebase, not realizing I was on an old topic branch. To transfer them, I wanted to stash them and then apply them to a new branch off of master. I used git stash pop
to transfer work-in-progress changes to this new branch, forgetting that I hadn't pulled new changes into master before creating the new branch. This resulted in a bunch of merge conflicts and loss of a clean stash of my changes (since I used pop).
Once I recreate the new branch correctly, how I can I recover my stashed changes to apply them properly?
Upvotes: 993
Views: 610662
Reputation: 10492
The simplest command, it works everywhere including git stash pop
, git merge
etc.
But careful! You'll lose all changes on untracked files. Tracked files stays intact
git reset --merge
Upvotes: 145
Reputation: 1923
git checkout -f
must work, if your previous state is clean.
CAUTION: Beware–you'll lose all untracked changes to your files.
Upvotes: 40
Reputation: 2001
If you're like me and had unstaged changes that you want to preserve, you can avoid losing that work by checking out a known stable version of each individual file from the stash
. Hopefully those files are different than the ones you were working on. Also, this is why we use small commits as we go, dumb dumb.
git checkout main -- <file_with_conflicts>
Upvotes: 2
Reputation: 15877
Luckily git stash pop
does not change the stash in the case of a conflict!
So nothing, to worry about, just clean up your code and try it again.
Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop
again and you get the same stash, that conflicted before.
Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.
Upvotes: 535
Reputation: 13350
Instructions here are a little complicated so I'm going to offer something more straightforward:
git reset HEAD --hard
Abandon all changes to the current branch
...
Perform intermediary work as necessary
git stash pop
Re-pop the stash again at a later date when you're ready
Upvotes: 47
Reputation: 36671
As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:
git reset HEAD .
(note the trailing dot)git stash
git checkout master
git fetch upstream; git merge upstream/master
git checkout new-branch; git rebase master
git stash apply stash@{1}
Upvotes: 1124