DEV Community

Cover image for git switch and git restore, or why not using git checkout
Christophe Colombier
Christophe Colombier

Posted on

git switch and git restore, or why not using git checkout

git checkout command exists since the beginning of git

It is used for these things:

  • creating new branch

git checkout -b new-feature upstream/main

  • switching branch

git checkout main

  • restoring unstaged changes

git checkout README.md

  • checking out code from other branch

git checkout v1.0.0 -- README.md

git checkout command confuses everyone who start using git

Why?

Because it mixes two concepts:

  • branches juggling
  • restoring files

That's why new commands were added with Git 2.23 (August 2019, almost 5 years ago):

git restore can be used as a simple replacement on action on files.

the only noticeable changes between git switch and git checkout is that branch creation was done with git checkout -b name while it's now git switch -c name

Image description

Credit: https://twitter.com/_risacan_/status/1162539626373865472

Top comments (3)

Collapse
 
riturajborpujari profile image
Rituraj Borpujari

For me git checkout seemed simple enough to use for the purposes. Didn't try switch because I thought, well checkout does it anyway (and maybe I got habituated with the -b).

That's why new commands were added with Git 2.23 (August 2019, almost 5 years ago):

Nice to know about the history here.

Collapse
 
ccoveille profile image
Christophe Colombier

Everyone should give a try to git switch and git restore.

My main problem is that git new comers lean the old git checkout that is so confusing at first

Collapse
 
pavelee profile image
Paweł Ciosek

It’s worth mention that git switch is useful to switch to branch that exists only in remote. It works like a shortcut 😎

Docs:
Image description

I’m using it before code review to switch to prepared branch with changes