The cool git: Git switch
TL;DR: Changes branches.
For humans: Stop using the overloaded checkout
and use the safe switch
.
Switching branches is probably one of the first things you learn when you start using git. With the checkout
command handy, you go from your bugfix
branch to the main
to fetch, merge and push and finish that pesky task, and then you start learning all what git checkout
is capable of.
You panic knowing that an innocent branch autocomplete can also delete all your changes.
This was the thought process of the Git team and they decided to fix in a retro compatible way.
** Introducing: git switch
**
This command, much smaller in surface does only one thing: switching branches. It also has very few options, but let's see it with an example.
Let's say your repo has these branches:
> git branch
* feature
master
dev
You want to jump to another branch? Use switch
> git switch dev
Switched to branch 'dev'
Your branch is up to date with 'origin/dev'.
Look at that, it checks if we are up to date, but what happens if we aren't?
You want to jump to the main branch? Use switch
> git switch main
Switched to branch 'main'
Your branch is behind 'origin/main' by 6 commits, and can be fast-forwarded.
Want to go back? You guessed it, use switch
> git switch -
Switched to branch 'dev'
You want to create another branch? Use switch
> git switch -c bugfix
Switched to a new branch 'bugfix'
> git branch
* bugfix
dev
master
feature
But the aha! moment comes when you switch
to a remote branch
git switch feature/other-remote-branch
Switched to a new branch 'feature/other-remote-branch'
branch 'feature/other-remote-branch' set up to track 'origin/feature/other-remote-branch'.
And what happens when you try a file with switch
? Nothing!
git switch package.json
fatal: invalid reference: package.json
And this is a feature. No more losing your files for autocompleting as with checkout