git checkout and
git switch are being used for checking out Git branches with
git switch being introduced recently (3 years ago) considering Git being “born” in 2005. So, why should one use
git switch instead of
git checkout. Let’s briefly point that out.
Checking out and switching are used interchangeably.
Quoting the official summary description:
git-checkout - Switch branches or restore working tree files
In other words,
git checkout is an ancient Git command that allows us to create and switch between branches, commits, pull requests, as well as recovering deleted branches, commits and files, and what not. For instance: Restore a deleted Git commits.
You can think of it as a swiss army knife type of command, since you will most likely use it for almost every quick fix out there.
Now, regarding branches, under the hood
git checkout does few other things beside switching, including:
- copying files from the current stage to the working tree.
- copying files from some tree-ish (whatever that is: directory, a commit or a reference) to the working tree.
No wonder that for most users it might become a source of confusion. Therefore,
git checkout was split into two separate commands:
git switch and
git switch / git restore
According to the official summary description:
git-switch - Switch branches
git switch a decent, relatively new command as it was being part of Git release 2.23 back in 2019 along with
git-restore - Restore working tree files
Related post: Restore deleted files in Git.
You might want to use
git switch for two simple operations only: creating and switching between branches. That’s the main idea behind it.
To create and switch to a new branch, run:
git checkout -b <new-branch> or
git switch -c <new-branch>
To switch to an already existing branch, run:
git checkout <branch> or
git switch <branch>
To discard file changes, run:
git checkout -- <filename> or
git restore <filename>
If you are just trying to create, checking out a new branch or, switching between already existing ones, for the most part use
git switch whenever possible.