Skip to content

Git Switch and Git Restore: The Modern Replacement for Git Checkout ​

git checkout does two completely different things: switch branches and restore files. Git 2.23 (August 2019) split those responsibilities into git switch and git restore. Adopting the split commands eliminates a class of accidents where a branch switch damages staged changes or a restore unexpectedly detaches HEAD.


1. The Problem with Git Checkout ​

git checkout is the most overloaded command in Git. In one session you might use it for three different operations:

bash
# Switch to a branch
git checkout feature/plumbus

# Restore a file from HEAD
git checkout -- main.go

# Detach HEAD to inspect an old tag
git checkout v1.0.0

Each of those invocations has a different semantic, and the wrong one at the wrong time can silently destroy work. The most common accidents:

  • git checkout somefile when you meant git checkout -- somefile (the first form detaches HEAD; the second restores the file).
  • git checkout . in a dirty working tree throws away all uncommitted changes with no confirmation.
  • git checkout <branch> refuses to run if it would overwrite uncommitted files, but the error message is opaque and beginners often force-past it with -f.

The split commands make intent explicit.


2. Git Switch: Branch Operations Only ​

git switch handles everything related to changing the current branch or HEAD. It cannot restore files, and it cannot accidentally detach HEAD without the --detach flag.

Basic Branch Switching ​

bash
# Switch to an existing branch
git switch main

# Create and switch to a new branch (like checkout -b)
git switch -c feature/pipeline-cache

# Switch to a remote tracking branch (creates a local tracking branch)
git switch -c staging origin/staging

Safe Switch with Stash Integration ​

git switch can auto-stash dirty work before switching and auto-populate it when you come back:

bash
# Auto-stash local changes, switch, then pop when switching back
git switch --merge feature/x

# Discard local changes and force the switch (irreversible)
git switch --discard-changes feature/x

Without --merge or --discard-changes, git switch refuses to switch if it would overwrite dirty files. This is safer than git checkout which would either refuse with a confusing error or proceed silently depending on the context.

Detaching HEAD (Explicit Only) ​

bash
# Detach HEAD at a tag (must pass --detach)
git switch --detach v2.4.0

# Detach at a commit SHA
git switch --detach a1b2c3d

# Without --detach, switch refuses to detach
git switch v2.4.0
# error: a branch is expected, got tag 'v2.4.0'

Return to Previous Branch ​

bash
# Switch back to the previous branch you were on
git switch -

# Like `git checkout -` but the hyphen is unambiguous

List Remote Tracking Branches ​

bash
# List all branches including remote-tracking
git switch --list

# Or use the dedicated command
git branch --list -a

3. Git Restore: File Operations Only ​

git restore handles restoring working-tree files and/or the index from any source. It cannot change branches.

Restore Working Tree from HEAD ​

bash
# Discard uncommitted changes to a file (like checkout -- <file>)
git restore main.go

# Discard all uncommitted changes (with confirmation)
git restore .

Restore Working Tree from a Specific Commit ​

bash
# Restore a file as it existed in a specific commit
git restore --source a1b2c3d main.go

# Restore from a tag
git restore --source v2.4.0 config/prod.yaml

# Restore from another branch
git restore --source feature/x deploy/helm/values.yaml

Staged (Index) Operations ​

bash
# Unstage a file (like reset HEAD <file>)
git restore --staged main.go

# Unstage AND restore working tree (complete undo of git add + edits)
git restore --staged --worktree main.go

# Stage a file from a specific commit (overwrite staged content)
git restore --source a1b2c3d --staged main.go

Selective Restoration with Pathspecs ​

bash
# Restore only files matching a pattern
git restore -- '*.go'

# Restore files in a directory, excluding tests
git restore -- ':!:*_test.go' 'src/'

Interactive Restoration ​

bash
# Interactively select hunks to restore (like checkout -p)
git restore --patch main.go

4. DevOps CI/CD Patterns ​

Pattern 1: Safe Branch Switching in CI Scripts ​

In CI pipelines, scripts often need to check out multiple branches to produce release artifacts or run matrix builds. Using git switch prevents accidental file loss:

bash
# CI pipeline: build release branch, then switch back to main
git switch --discard-changes release/2.4
make build-release
git switch --discard-changes main

Without --discard-changes, the pipeline fails fast if the working tree is dirty rather than silently dropping changes.

Pattern 2: Restoring Configuration from Git in Deploy Scripts ​

When a deploy script needs to pull a specific version of a config file from a release tag without touching the rest of the working tree:

bash
# Restore prod config from the release tag
git restore --source v2.4.0 -- config/production.yaml

# Restore multiple config files from different sources
git restore --source v2.4.0 -- config/
git restore --source v2.4.0 -- docker-compose.yml

Compare with the old approach using git checkout which risked detaching HEAD if you forgot the -- separator.

Pattern 3: Selective Unstage in CI Artifact Validation ​

After a CI pipeline stages generated artifacts (unexpectedly), restore only the index to undo the staging without touching working-tree files that might contain build outputs needed for debugging:

bash
# Unstage everything but keep working tree intact
git restore --staged .

# Or unstage specific generated files
git restore --staged -- 'dist/*.js'

Pattern 4: Git Bisect Helper Restoration ​

When using git bisect run, the test script often needs to restore specific files to a known state before running tests. Using git restore with --source is explicit and safe:

bash
# Inside a bisect run script: restore config to match the commit
git restore --source HEAD -- config/ci.yml

# Run tests, then restore the bisect checkout
./run-tests.sh

Pattern 5: Emergency File Recovery Across Branches ​

Restore a file that was accidentally deleted in the current branch from its state in another branch:

bash
# Restore deploy/helm/values.yaml from main branch
git restore --source main -- deploy/helm/values.yaml

# The file is now in the working tree and index as it exists on main
# Stage and commit to bring it back
git add deploy/helm/values.yaml
git commit -m "fix: restore deleted helm values from main"

5. Migration Guide for Teams ​

Step 1: Add Shell Aliases ​

bash
# ~/.bashrc or ~/.zshrc
alias gco='git switch'
alias grs='git restore'
alias gcb='git switch -c'

Step 2: Pre-commit Hook to Warn on Git Checkout ​

Install a pre-commit hook that warns when git checkout is used in a context that could be ambiguous:

bash
#!/bin/sh
# .git/hooks/pre-commit (or shared via hooks-manage.sh)
if git rev-parse --verify HEAD >/dev/null 2>&1; then
  against=HEAD
fi

# No enforcement — just a note in CI lint output

For stricter enforcement, add a CI lint step that scans scripts for git checkout and suggests the split commands:

bash
# CI lint job
if grep -rn '\bgit checkout\b' scripts/ --include='*.sh' | grep -v 'checkout-index'; then
  echo "warning: prefer 'git switch' and 'git restore' over 'git checkout'"
fi

Step 3: Deprecate Checkout in Contribution Guidelines ​

Add a note to CONTRIBUTING.md:

This repository prefers git switch for branch operations and git restore for file operations. The old git checkout command is ambiguous between these two uses. See docs/devops-workflows/git-switch-restore.md for migration.


6. Command Mapping Reference ​

Old git checkout UsageNew Command
git checkout <branch>git switch <branch>
git checkout -b <branch>git switch -c <branch>
git checkout -git switch -
git checkout <tag>git switch --detach <tag>
git checkout <commit>git switch --detach <commit>
git checkout -- <file>git restore <file>
git checkout <commit> -- <file>git restore --source <commit> <file>
git checkout HEAD -- <file>git restore <file>
git checkout -pgit restore --patch
git checkout -- .git restore .
git checkout -- <file> (discard)git restore --worktree <file>
git reset HEAD <file> (unstage)git restore --staged <file>
git reset HEAD --hardgit restore --staged --worktree .

Note: git checkout-index and git checkout --detach (the original plumbing) have no direct replacement and remain valid.


7. Edge Cases and Pitfalls ​

Pitfall 1: --discard-changes is Unrecoverable ​

git switch --discard-changes discards working-tree changes with no reflog backup for those changes. Use --merge to auto-stash instead:

bash
# Safe: auto-stash before switching
git switch --merge feature/x

# Dangerous: discards uncommitted work
git switch --discard-changes feature/x

Pitfall 2: Restore Does Not Create Commits ​

git restore modifies the working tree and/or index but does not stage or commit. After restoring a file from another branch, you must explicitly git add and git commit to record the change.

Pitfall 3: Restore with --source Does Not Merge ​

When you restore a file from another branch, you get the exact file content from that branch, not a three-way merge. If the file has diverged, the restore overwrites your working tree content entirely.

bash
# This overwrites config.yml with the exact version from main
git restore --source main config.yml

Use git merge-file or a proper merge if you need to combine changes.

Pitfall 4: Switch Rejects Dirty Worktree by Default ​

This is by design. If git switch refuses with:

error: Your local changes to the following files would be overwritten...

You have three options:

bash
# 1. Commit the changes
git add -A && git commit -m "wip"

# 2. Stash them
git stash push -m "before-switch"
git switch feature/x
git stash pop  # when you come back

# 3. Discard them (permanent)
git switch --discard-changes feature/x

Pitfall 5: Git Version Compatibility ​

CI runners on older Git versions (pre-2.23) do not support git switch or git restore. Check the runner's Git version before migrating scripts:

bash
# CI compatibility check
if [ "$(git --version | cut -d' ' -f3 | cut -d. -f1)" -lt 2 ] || \
   [ "$(git --version | cut -d' ' -f3 | cut -d. -f2)" -lt 23 ]; then
  echo "Using fallback: git checkout"
  git checkout "$branch"
else
  git switch "$branch"
fi

Forgejo/GitHub Actions hosted runners typically ship Git 2.40+. Self-hosted runners on older OS releases may still run Git 2.17 or earlier.


8. Summary ​

Criteriongit checkoutgit switch + git restore
Intent clarityAmbiguousExplicit per command
Detached HEAD safetyAccidentalRequires --detach flag
File restore safetyNeeds -- separatorDedicated command
Unstage operationVia git resetgit restore --staged
Auto-stash on switchNot built-in--merge flag
CI script clarityError-proneSelf-documenting
Minimum Git versionAny2.23+

Adopting git switch and git restore eliminates an entire class of repository accidents. The commands are not just syntactic sugar: they encode safety defaults that prevent the most common git checkout foot-guns. For DevOps pipelines where a wrong checkout can silently corrupt a release artifact, the split commands are the safer choice.

Git Master — Git Reference for Every Skill Level