git switch --detach: Usage, Options & Common CI Errors
git switch --detach moves HEAD onto a commit directly, with no branch attached.
Detaching is exactly what CI does when it builds a specific SHA or tag. Knowing the detached-HEAD model prevents the classic "I committed and lost it" surprise on runners.
What it does
git switch --detach points HEAD at a commit, tag, or remote ref without making it a branch. New commits made here are reachable only from HEAD until you create a branch for them.
Common usage
git switch --detach <sha>
git switch --detach v1.2.0
git switch --detach origin/main
# keep work made while detached:
git switch -c rescueOptions
| Flag | What it does |
|---|---|
| --detach | Switch to a commit in detached HEAD |
| <sha> / <tag> / <ref> | The commit-ish to detach onto |
| -c <name> | Re-attach by creating a branch here |
| --discard-changes | Drop local changes when switching |
Common errors in CI
fatal: a branch is expected, got commit ‘<sha>’ - plain git switch refuses a commit; add --detach. After detaching, "You are in ‘detached HEAD’ state… commits you make will not belong to any branch" warns that new commits are orphaned; create a branch (git switch -c) before switching away to keep them.
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.
- 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