January 9th, 2022

git-switch.png

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 your-new-branch

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

Follow @LaravelMagazine on Twitter →
Marian Pop

I’m a Full-Stack Developer based in Transylvania. I use Laravel daily whether it’s for work or my personal projects.

Newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox every Friday!

We'll never share your email address and you can opt out at any time.