Skip to content
Latchkey

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.

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.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →