Skip to content
LatchkeyLatchkey home

git checkout Command: Switch Refs in CI

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

Key takeaways

  • Use --detach with a SHA to build exactly the commit that triggered the pipeline.
  • -b creates and switches to a new branch in one step for automation that pushes.
  • Modern scripts often prefer git switch for branch changes and git restore for files.

Frequently asked questions

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.

Related guides

References

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