git checkout is the classic command to switch branches and restore files.
checkout still works everywhere, but switch and restore split its two jobs more clearly. Know its detached-HEAD behavior in CI.
What it does
git checkout updates HEAD and the working tree to match a branch, tag, or commit, and can also restore individual files from a commit into the working tree.
Common usage
Terminal
git checkout main
git checkout -b feature # create and switch
git checkout <sha> # detached HEAD at a commit
git checkout -- file.txt # discard working-tree changes
git checkout origin/main -- path/to/file
Options
Flag
What it does
-b <name>
Create a new branch and switch to it
-B <name>
Create or reset a branch and switch
--detach
Check out a commit without a branch
-- <path>
Restore file(s) instead of switching
-f / --force
Discard local changes when switching
Common errors in CI
error: Your local changes to the following files would be overwritten by checkout - commit or stash first. CI often lands in "detached HEAD" because it checks out a SHA; that is expected. "pathspec did not match" usually means a missing ref because of a shallow clone.
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@v4with:fetch-depth:0 # history, tags, and git describe all need this- run:|git rev-parse --is-shallow-repository # expect falsegit rev-parse --abbrev-ref HEAD # prints HEAD when detached
Frequently asked questions
git checkout: Usage, Options & Common CI Errors?
checkout still works everywhere, but switch and restore split its two jobs more clearly. Know its detached-HEAD behavior in CI.
What it does?
git checkout updates HEAD and the working tree to match a branch, tag, or commit, and can also restore individual files from a commit into the working tree.
Common errors in CI?
error: Your local changes to the following files would be overwritten by checkout - commit or stash first. CI often lands in "detached HEAD" because it checks out a SHA; that is expected. "pathspec did not match" usually means a missing ref because of a shallow clone.