The git switch command is the instruction to switch the working context between different branches within Git.
We’ve already seen how to create and delete branches. The next step is to learn how to switch the branch we are working on.
In this entry, we will analyze git switch, the standard tool for switching between branches.
In the past, if you wanted to switch branches in Git, you used git checkout. The problem, as we saw in the article about git restore, is that checkout served many purposes: switching branches, restoring files, traveling to individual commits…
In Git version 2.23 (2019), the Git developers decided to bring order and created a specific command for the most common task in the workflow: switching branches.
Switching Branches
The basic function is to move your HEAD pointer and update your working directory to match the target branch.
If you are on main and want to move to develop:
git switch develop
What happens?
- Git moves the
HEADpointer to point to thefeaturelabel. - Git updates the files in your folder (Working Directory) to be identical to the snapshot saved in the last commit of
feature.
If you have files open in your code editor, you will see them change instantly before your eyes when you execute the command.
The “Go Back” Button (-)
This is a time-saving trick. Imagine you are working on feature/login and need to go to main for a moment to check something, and then return to feature/login.
Instead of typing the names all the time, you can use the hyphen:
git switch -
This command means: “Go back to the branch I was on just before this one”. It’s like the “Previous Channel” button on the TV remote or cd - in Linux.
Create and Switch at the Same Time
In the previous article, we saw that git branch new-branch created the branch but left you “stranded” on the old one. You had to do two steps.
The usual workflow is to create a branch and immediately jump to it to start working. With git switch, we use the -c (create) option:
git switch -c feature
What happens?
- It creates the
featurebranch at the current commit. - It automatically switches you to it.
What Happens to My Unsaved Changes?
If you have modified files and try to switch branches:
- If there is no conflict: (The file you touched is the same in both branches) Git takes your changes to the new branch. It’s very convenient.
- If there is a conflict: (The file you touched is different in the target branch) Git will abort the operation and warn you:
error: Your local changes to the following files would be overwritten by checkout:
config.js
Please commit your changes or stash them before you switch branches.
Aborting
Git protects us from losing work. To solve it, you have two options: make a commit in your current branch or use git stash (which we’ll see later) to save them temporarily.
