# git checkout Command: Switch Refs in CI

> git checkout switches branches or restores files. Reference for checking out a branch, --detach, and -b to create branches in automated CI scripts.

Source: https://latchkey.dev/learn/command-reference/git-checkout-command-reference  
Updated: 2026-06-26

git checkout switches the working tree to a branch, tag, or commit, and can create branches.

In CI you typically check out a specific ref the pipeline was triggered for. checkout is the long-standing command for this; newer scripts often prefer git switch for branches.

## Common flags

- `<branch>` - switch to an existing branch and update the working tree
- `-b <new-branch>` - create a new branch and switch to it
- `--detach` - check out a commit in detached HEAD state (common for tags and SHAs)
- `--force` / `-f` - discard local changes when switching
- `<commit> -- <path>` - restore a file from another commit

## Example

```shell
# Check out the exact commit that triggered the build
git checkout --detach "${GIT_SHA}"
# Create a release branch in an automation job
git checkout -b "release/${VERSION}"
```

## In CI

Checking out a SHA with --detach is the safe, deterministic way to build the exact commit a webhook delivered. CI checkout actions usually leave you in detached HEAD already, so create a branch with -b only when a job needs to push.

## 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
```

> `git rev-parse --abbrev-ref HEAD` returns the literal string `HEAD` on a detached checkout rather than a branch name. On GitHub Actions read `github.ref_name` instead; the git command cannot know what it was checked out for.

## FAQ

### git checkout Command: Switch Refs in CI?

In CI you typically check out a specific ref the pipeline was triggered for. checkout is the long-standing command for this; newer scripts often prefer git switch for branches.

### In CI?

Checking out a SHA with --detach is the safe, deterministic way to build the exact commit a webhook delivered. CI checkout actions usually leave you in detached HEAD already, so create a branch with -b only when a job needs to push.

---

Latchkey runs CI/CD that repairs its own failures. Agent entry points: https://latchkey.dev/agent.txt, https://latchkey.dev/openapi.json, https://latchkey.dev/llms.txt
