git switch - What’s the difference with git checkout?

Eugenio Contreras
2 min readNov 16, 2022

--

Almost three years ago, Git released Git 2.23 with the introduction of a few commands that, at least from my experience are not widely used yet, git switch and git restore.

This is why I’d like to give a brief introduction to git switch and the main differences with git checkout.

If you go to the documentation, you may be wondering why Git introduced a command that behaves similarly to git checkout. The thing is, at first, it seems this is true but git switch comes to do one task in particular, as his name refers, to switch and/or create branches. On the other hand, it turns out that git checkout can do quite a lot.

The mostly uses case for git checkout is to switch branches or create a new one, but actually, you can change files too. If you write git checkout <filename>, it will reset your working copy of the file and make it equivalent to the working index. This is always the case if, for example, you modify a file without staging the changes. You will remain in the same branch after that, but your file will be restored. This can’t be achieved by git switch.

In this aspect, it’s starting to feel a bit confusing, and the purpose of introducing git switch is for that reason, to have a command for one task in particular and decouple a few functionalities from git checkout.

Although git switch is still listened to as experimental in the documentation.

THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.

It’s good to mention that git switch has a few limitations, though. If you want to change branches in the middle of a merge using the --force flag, you can do it with git checkout but not with git switch. The difference is in this line of the documentation

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

That’s why it will throw an error if you try to do that with git switch.

In resume, git switch is a pretty straightforward command and just came to achieve one task, it was specifically created for that. For new users is a good practice and easy to remember, and having two commands (git switch and git restore) for different functionalities instead of just one (git checkout) can make life easier for new git users.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Eugenio Contreras
Eugenio Contreras

Written by Eugenio Contreras

from coffee import * ☕️ Data Architect & Engineer 👨🏻‍💻

No responses yet

Write a response