Skip to content
LatchkeyLatchkey home

git switch: Usage, Options & Common CI Errors

git switch is the modern command dedicated to changing branches.

switch handles branch movement only, so it is harder to misuse than checkout. Use restore for files.

What it does

git switch moves HEAD to another branch and updates the working tree. It can create a branch with -c but will not restore files.

Common usage

Terminal
git switch main
git switch -c feature           # create and switch
git switch -                    # back to previous branch
git switch --detach <sha>
git switch -c local origin/remote   # create tracking branch

Options

FlagWhat it does
-c <name>Create a new branch and switch
-C <name>Create or reset a branch and switch
--detachSwitch to a commit in detached HEAD
--track / -tSet up upstream tracking
--discard-changesThrow away local changes when switching

Common errors in CI

fatal: invalid reference: <name> - the branch does not exist locally (common after a shallow/single-branch clone). Fetch it first, or use git switch -c <name> origin/<name>. Like checkout, "your local changes would be overwritten" means commit or stash before switching.

Using this in CI

CI checkouts are shallow and detached by default, which changes the answer this command gives you. Commands that read history, branch names, or tags need the checkout configured for it.

.github/workflows/ci.yml
- uses: actions/checkout@v4
  with:
    fetch-depth: 0   # history, tags, and git describe all need this

- run: |
    git rev-parse --is-shallow-repository   # expect false
    git rev-parse --abbrev-ref HEAD          # prints HEAD when detached

Frequently asked questions

git switch: Usage, Options & Common CI Errors?
switch handles branch movement only, so it is harder to misuse than checkout. Use restore for files.
What it does?
git switch moves HEAD to another branch and updates the working tree. It can create a branch with -c but will not restore files.
Common errors in CI?
fatal: invalid reference: <name> - the branch does not exist locally (common after a shallow/single-branch clone). Fetch it first, or use git switch -c <name> origin/<name>. Like checkout, "your local changes would be overwritten" means commit or stash before switching.

Related guides

References

Run this faster and cheaper on Latchkey managed runners - self-healing included. Start free → 30-day trial · No credit card