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.
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.
Related guides
git checkout Command: Switch Refs in CIgit checkout switches branches or restores files. Reference for checking out a branch, --detach, and -b to cr…
git symbolic-ref Command in CIgit symbolic-ref reads and sets symbolic refs like HEAD. Reference for finding a remote default branch reliab…
git rev-parse Command: Resolve Refs in CIgit rev-parse resolves refs to SHAs and prints repo metadata. Reference for HEAD, --short, and --abbrev-ref t…
git reset Command: Move HEAD in CIgit reset moves HEAD and optionally the index and working tree. Reference for --hard and --soft to roll back…