Read more

Git: Switch

Julian
October 07, 2022Software engineer at makandra GmbH

tl;dr

git checkout is the swiss army of git commands. If you prefer a semantically more meaningful command for branch related tasks, use git switch instead.

You can use git switch since git 2.23.

Switch Branch

git branch
# * master
#   feature-branch

git switch feature-branch
git branch
#   master
# * feature-branch

git switch -
git branch
# * master
#   feature-branch

Info

For this use case you can of course also use git checkout.

Switch on a Remote Branch

git branch -a
# * master
#   remotes/origin/HEAD -> origin/master
#   remotes/origin/remote-feature-branch

git switch remote-feature-branch
git branch -a
#   master
# * remote-feature-branch
#   remotes/origin/HEAD -> origin/master
#   remotes/origin/remote-feature-branch

Info

This is also working with git checkout

Create a New Branch

git branch
# * master

git switch --create new-feature-branch
git branch
#   master
# * new-feature-branch

Hint

You can also use the short version git switch -c.

Info

git checkout -b is doing the same.

Temporary Inspection

git switch HEAD~3
# fatal: a branch is expected, got commit 'HEAD~3'

git switch --detach HEAD~3
git branch
# * (HEAD detached at git-hash)
#   master

Hint

You can also use the short version git switch -d.

Info

With git checkout you can achieve the same.

Sources

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot
Julian
October 07, 2022Software engineer at makandra GmbH
Posted by Julian to makandra dev (2022-10-07 11:10)