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
Flag
What it does
-c <name>
Create a new branch and switch
-C <name>
Create or reset a branch and switch
--detach
Switch to a commit in detached HEAD
--track / -t
Set up upstream tracking
--discard-changes
Throw 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@v4with:fetch-depth:0 # history, tags, and git describe all need this- run:|git rev-parse --is-shallow-repository # expect falsegit 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.