Skip to content
LatchkeyLatchkey home

git switch Command: Change Branches in CI

git switch moves HEAD to a different branch, with a clearer, branch-only interface than checkout.

git switch was introduced to split branch switching from file restoring. In CI it makes scripts more readable and less error-prone than the overloaded git checkout.

Common flags

  • <branch> - switch to an existing branch
  • -c <new-branch> / --create - create a new branch and switch to it
  • -C <branch> / --force-create - create or reset the branch to the current commit
  • --detach - switch to a commit in detached HEAD state
  • --discard-changes - throw away local changes when switching

Example

shell
# Create a working branch for an automated commit
git switch -c "ci/update-${RUN_ID}"
# Detach onto a tag to build a release
git switch --detach "v${VERSION}"

In CI

Prefer git switch over git checkout in new pipeline scripts: it only touches branches, so a typo cannot accidentally overwrite files the way checkout can. Use --detach for tags and SHAs.

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

Key takeaways

  • git switch -c is the readable way to create a branch in automation.
  • switch cannot accidentally clobber files, unlike the overloaded checkout.
  • Use --detach to build a specific tag or commit.

Frequently asked questions

git switch Command: Change Branches in CI?
git switch was introduced to split branch switching from file restoring. In CI it makes scripts more readable and less error-prone than the overloaded git checkout.
In CI?
Prefer git switch over git checkout in new pipeline scripts: it only touches branches, so a typo cannot accidentally overwrite files the way checkout can. Use --detach for tags and SHAs.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card