What's the Difference Between Git Switch and Checkout?
You can use both git checkout and git switch for switching between branches. But why do we have two commands for the same thing?
When you start learning and using Git, you'll come across the common situation where you have to change branches.
And here, things could become a bit confusing for you. If you look for how to switch branches in git, you'll come across some examples where git switch is used and some examples where git checkout is used.
Git checkout command | Git switch command | Description |
---|---|---|
git checkout my-branch | git switch my-branch | Switch to branch my-branch |
git checkout -b my-branch | git switch -c my-branch | Create and switch to my-branch |
So, what's the difference between git switch and git checkout? If both can be used for switching branches, why are there two commands for the same purpose? Let me explain.
Difference between git checkout and git switch
Here's the thing. Git checkout is the old command which was used to create and switch branches. It can also be used to restore changes from a certain commit. But git checkout does more than that. It allows you to copy files from any branch or commit directly into your working tree without switching branches.
As Dan Fabulich notes, git checkout does three things:
- switch branches
- copy files from the stage to the working tree
- copy files from a tree-ish to the working tree
If you don't understand it, that's okay. Just remember that git checkout does more than simple branch switching and the additional functionalities started creating confusion.
And hence, with the release of Git 2.23, its developers introduced two new git commands: git switch
and git restore
.
The idea behind this move is to let people use git switch
for switching branches and git restore for undoing changes from a commit. At the same time git checkout
remains there for advanced options to deal with tree-ish.
Which one should you use? Git checkout or git switch?
If you have to switch branches, use the git switch command instead of git checkout. Why? Because it was created for this specific task. For new Git users, it is easier to remember that git switch
is for switching branches, git restore
is for restoring a commit.
So, it's a good practice to replace the branch creation and switching functionality of git checkout with git switch command.
I hope you are clear about using git switch and checkout now. If you have anything to add, please use the comment section.
Creator of Linux Handbook and It's FOSS. An ardent Linux user & open source promoter. Huge fan of classic detective mysteries from Agatha Christie and Sherlock Holmes to Columbo & Ellery Queen.