27

I was accidentally working on the wrong branch. Now I want to transfer all my changes to the correct branch.

If I stash the changes and apply them on the correct branch, will it only add the uncommitted changes to the correct branch or every change/commit from the wrong branch that doesn't exist on the correct branch?

For example

Wrong branch has:

  • Commit a

  • Uncommitted Changes b

Correct branch has

  • Commit c

If I do git stash on the wrong branch and git apply stash in the correct branch, will it transfer commit a to the correct branch?

MeesterPatat
  • 2,671
  • 9
  • 31
  • 54

5 Answers5

15

I would do one stash, then reset (mixed so you don't lose the changes) the a commit, stash that, then change to the correct branch and pop both stashes.

git stash save "b"
git reset HEAD~
git stash save "a"
git checkout correct-branch
git stash pop
git commit -m "a"
git stash pop
miguel_ibero
  • 1,024
  • 7
  • 9
  • Can you please explain what you are doing? I don't understand why you do `git reset HEAD~ git stash save "a" ` – likejudo Nov 19 '21 at 20:14
  • @likejudo the reset step moves the git to the previous commit, then stash it as "a" – weasel Mar 31 '22 at 03:38
15

If your branch doesn't exist yet:

  • git stash branch "new_branch"

if it does:

  • git stash
  • git stash branch "temp_new_branch"
  • git add "your changes"
  • git commit
  • git checkout "your desired branch to apply stash"
  • git merge "temp_new_branch"
  • git push
  • git branch -d "temp_new_branch"
likejudo
  • 3,396
  • 6
  • 52
  • 107
miguelfg
  • 1,455
  • 2
  • 16
  • 21
  • `no stash entries found` when I try `git stash branch "temp_new_branch" ` – likejudo Nov 19 '21 at 20:27
  • If anyone can look at that second option, and still love git... Well, you and I would not get along... – spechter Oct 19 '22 at 10:30
  • @spechter well... any alternatives? I don't think love has anything to do with it. It's still the most efficient solution (for now). Besides, this is an issue specific to stashes, which are "sort of" a parallel reality to your work flow. So the fact that there is a workflow to solve something, I think that's great. – Lockszmith Apr 05 '23 at 14:35
6

Workaround

  1. Make a commit with those desired changes.
  2. Checkout to the branch you want those changes to be on.
  3. From that branch git cherry-pick 23h123kjb(<-- replace this hash with the one found in a git log specific to the commit you want to bring in)
  4. Profit!
dYale
  • 1,541
  • 1
  • 16
  • 19
1

No it won't. Commits are not put in the Stash. I also sometimes just switch branches with my changes uncommitted and unstashed and it also works (not sure if in every case, though).

0

What you can also do:

  • Create a patch on the 'wrong' branch.
  • Discard the changes
  • Switch to the correct branch
  • Apply the patch on that branch
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98