How to Move Existing, Uncommitted Work to a New Branch in Git


Filed Under Snippets, Tutorials

So here’s a new one for ya.

I was working on a branch all day, closed the laptop, went home and fell asleep. Nothing out of the ordinary. The next day, I awoke, and upon returning to work, immediately began working on a new problem.

The issue arose when I discovered to my horror that I was still on the same branch from yesterday! *Gasp*

Lest we forget, we have Git at our disposal — so I take a breath and dive in:

git status

This will probably return a list of changes not staged like this:

On branch fix-from-yesterday
Your branch is up to date with 'origin/fix-from-yesterday-'.

Changes not staged for commit:
(use "git add …" to update what will be committed)
(use "git checkout -- …" to discard changes in working directory)
modified: project/api-v4.php
modified: web/assets/js/some-project/package.json

Now that we have a pulse on things, we can do this:

git checkout -b new-branch-of-changes-for-today

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

git add <the files you want commit>

and finally, commit to your new branch with ol trusty:

git commit -m "Make sure your description is short and sweet"

And there you have it! According to git-checkout documentation, -b and -B are interchangeable. Here’s the rub:

Specifying -b causes a new branch to be created as if git-branch[1] were called and then checked out. In this case you can use the --track or --no-track options, which will be passed to git branch. As a convenience, --track without -b implies branch creation; see the description of --trackbelow.

If -B is given, <new_branch> is created if it doesn’t exist; otherwise, it is reset. This is the transactional equivalent of

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: