git stash changes apply to new branch?

Git

Git Problem Overview


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 ?

Git Solutions


Solution 1 - Git

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

Solution 2 - Git

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.

Solution 3 - Git

If you have some changes on your workspace and you want to stash them into a new branch use this command:

git stash branch branchName

It will make:

> 1. a new branch (starting from the commit at which the stash was originally created) > 2. move changes to this branch > 3. and remove latest stash (Like: git stash pop)

After running this command, you will want to git add the changes and to commit them.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYD8877View Question on Stackoverflow
Solution 1 - GitAndrejs CainikovsView Answer on Stackoverflow
Solution 2 - GitRodney GolpeView Answer on Stackoverflow
Solution 3 - GitHamed YarandiView Answer on Stackoverflow