git checkout: Usage, Options & Common CI Errors
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/fileOptions
| 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.
Related guides
git switch: Usage, Options & Common CI Errorsgit switch changes branches with a focused, modern interface. Reference for -c, --detach, --track, and the er…
git restore: Usage, Options & Common CI Errorsgit restore discards working-tree changes or unstages files. Reference for --staged, --source, --worktree, an…
git branch: Usage, Options & Common CI Errorsgit branch lists, creates, renames, and deletes branches. Reference for -d, -D, -m, --set-upstream-to, and th…
git stash: Usage, Options & Common CI Errorsgit stash saves uncommitted changes aside and restores a clean tree. Reference for push, pop, -u, list, and t…