Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git stash changes apply to new branch?

Tags:

git

I was working on master branch, made some changes and then stashed them. Now, my master is at HEAD.

But now, I want to retrieve these changes but to a new branch which branches from the HEAD version of the master branch.

How do i do this ?

like image 691
YD8877 Avatar asked Aug 03 '11 10:08

YD8877


People also ask

Can I apply stash changes to different branch?

As you can see, you first need to stash changes before you can apply them to a new branch when using git stash branch .

How do I move stashed changes to a new branch?

If you have not made the commit yet, just run git stash . This will save away all of your changes. Switch to the branch you want the changes on and run git stash pop . There are lots of uses for git stash.

Is git stash tied to a branch?

Nope the you get a stack (last-in-first-out) of stashes. You push a stash to your stash-stack, then another then you pop out the 2nd then you pop out the first, etc. "No and No" is a confusing answer since the OP's first question is an either/or.

How do I bring changes to a new branch?

The git checkout -b <BranchName> command will create a new branch and switch to it. Moreover, this command will leave the current branch as it is and bring all uncommitted changes to the new branch.


2 Answers

Is the standard procedure not working?

  • make changes
  • git stash save
  • git branch xxx HEAD
  • git checkout xxx
  • git stash pop

Shorter:

  • make changes
  • git stash
  • git checkout -b xxx
  • git stash pop
like image 63
Andrejs Cainikovs Avatar answered Oct 06 '22 12:10

Andrejs Cainikovs


Since you've already stashed your changes, all you need is this one-liner:

  • git stash branch <branchname> [<stash>]

From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):

Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.

This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.

like image 38
Rodney Golpe Avatar answered Oct 06 '22 13:10

Rodney Golpe