Skip to content

/compare/git/git-switch-vs-git-checkout

git switch vs git checkout: which one to use

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · git version 2.55.0.windows.5updated
tool
Git
compares
git switch / git restore vs git checkout

Use git switch to change branches and git restore to undo changes in files; both arrived in Git 2.23 to split the two jobs of git checkout. git checkout still works and is not deprecated, but because it accepts both branch names and file paths, a typo can discard file changes instead of switching branches. The new commands only do one thing each.

Equivalents

Taskgit switch / restoregit checkout
Switch to a branchgit switch maingit checkout main
Create and switchgit switch -c featuregit checkout -b feature
Previous branchgit switch -git checkout -
Track a remote branchgit switch feature (from origin/feature)git checkout feature
Inspect an old commitgit switch --detach abc1234git checkout abc1234
Discard edits in a filegit restore app.jsgit checkout -- app.js
Unstage a filegit restore --staged app.jsgit reset app.js
File from another branchgit restore --source=main app.jsgit checkout main -- app.js

Safer by design

bash
git init -q -b main repo && cd repo
echo v1 > app.js && git add app.js && git commit -qm v1
first=$(git rev-parse --short HEAD)
echo v2 > app.js && git commit -qam v2
git switch "$first" 2>&1 | head -n 2
git switch -q --detach "$first" && git branch --show-current || true
git switch -q main
echo "local edit" > app.js
git switch app.js 2>&1 | head -n 1

Output

fatal: a branch is expected, got commit 'fa057d8'
hint: If you want to detach HEAD at the commit, try again with the --detach option.
fatal: invalid reference: app.js

git switch refuses to detach HEAD unless you say --detach, and refuses file paths entirely. git checkout app.js in the same situation would have silently thrown away the local edit.

Criterion by criterion

Criteriongit switch / restoregit checkout
Switch branchesgit switchyes
Create a branchgit switch -cgit checkout -b
Restore filesgit restoreyes, with -- PATH
Detached HEADonly with --detachimplicitly, for any commit
Ambiguous name (branch and file)impossibleneeds -- to disambiguate
AvailabilityGit 2.23+ (2019)every Git version

Sources