January 9th, 2022

Switch to a new branch with unstaged changes

Switch to a new branch with unstaged changes

You can switch your current HEAD branch with the switch command. It's new (introduced in Git v2.23) and offers a more straightforward alternative to the classic checkout command. The switch command is a simple replacement for checkout and it serves a very specific and limited purpose: branch switching and creation!

Changing branches before switch was available required using the checkout command, but if you had unstaged changes on the current branch, you had to stash the changes first, switch to a new branch, and then apply the stash to that branch. That's fine; it works, but switch allows you to perform all of these tasks with a single command.

If you are on the main branch and you want to switch to branch-B you can simply run the following command:

1git switch branch-B

The specified branch will become the new HEAD branch as a result of this. However, you can use the -c parameter to create a new local branch and switch to the newly created branch and have all of the unstaged changes in your new branch:

1git switch -c your-new-branch

For more details about how you can use the switch command, visit the official Git documentation.

Statamic Ninja

Comments

Marian Pop

PHP / Laravel Developer. Writing and maintaining @LaravelMagazine. Host of "The Laravel Magazine Podcast". Pronouns: vi/vim.

Subscribe to our newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.

Weekly articles
We send a new issue of the newsletter every week on Friday.
No spam
We'll never share your email address and you can opt out at any time.