Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move existing, uncommitted work to a new branch in Git

I started some work on a new feature and after coding for a bit, I decided this feature should be on its own branch.

How do I move the existing uncommitted changes to a new branch and reset my current one?

I want to reset my current branch while preserving existing work on the new feature.

like image 676
Dane O'Connor Avatar asked Sep 08 '09 15:09

Dane O'Connor


People also ask

What happens to uncommitted changes when you switch branches?

If the file is different on your other branch, Git will not let you switch branches, as this would destroy your uncomitted changes. It is safe to try switching branches, and if Git warns you that "uncommitted changes would be overwritten" and refuses to switch branches, you can stash your changes and try again.


1 Answers

Update 2020 / Git 2.23

Git 2.23 adds the new switch subcommand in an attempt to clear some of the confusion that comes from the overloaded usage of checkout (switching branches, restoring files, detaching HEAD, etc.)

Starting with this version of Git, replace the checkout command with:

git switch -c <new-branch> 

The behavior is identical and remains unchanged.


Before Update 2020 / Git 2.23

Use the following:

git checkout -b <new-branch> 

This will leave your current branch as it is, create and checkout a new branch and keep all your changes. You can then stage changes in files to commit with:

git add <files> 

and commit to your new branch with:

git commit -m "<Brief description of this commit>" 

The changes in the working directory and changes staged in index do not belong to any branch yet. This changes the branch where those modifications would end in.

You don't reset your original branch, it stays as it is. The last commit on <old-branch> will still be the same. Therefore you checkout -b and then commit.

like image 74
knittl Avatar answered Oct 08 '22 15:10

knittl