Git: Switch

Posted . Visible to the public.

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

Profile picture of Julian
Julian
License
Source code in this card is licensed under the MIT License.
Posted by Julian to makandra dev (2022-10-07 09:10)