Search code examples
gitgit-branchgit-commitgit-stash

Moving uncommitted changes to a new branch: git: stash vs checkout


I've done some changes to my code in branch1, but now I need to move those changes to another branch. Graphically, I have:

master
  |___develop
         |___branch1

and I need to move all the uncommitted changes and untracked files to a new branch branch2 (which does not exist):

master
  |___develop
         |___branch1
         |___branch2

after which I'll just delete branch1 since all its changes are already pushed, and be left with all the uncommitted changes and untracked files in branch2:

master
  |___develop
         |___branch2

There are quite a few of similar questions in SO but I'm still not sure how I should proceed in my case. Some say to use git stash (How do I merge my local uncommitted changes into another Git branch?, moving changed files to another branch for check-in) which in my case I guess would be:

git stash -u
git checkout develop
git checkout -b branch2
git stash pop

but other answers (Put current changes in a new Git branch, Moving uncommitted changes to a new branch) say to simply use checkout as:

git checkout -b branch2

but I'm not sure if this will carry my untracked files too. There's a newer answer that recommends using switch (Move existing, uncommitted work to a new branch in Git), but my git version 2.17.1 does not have this command.

Any help will be much appreciated.


Solution

  • Using stash is safer, as it avoids any problems that might pop up with switching branches with a dirty working directory. stash even has a subcommand for directly creating a branch from a stash.

    git stash -u
    git checkout develop
    git stash branch branch2