Synopsis
Description
git checkout has two main modes:
- Switch branches - with
git checkout <branch> - Restore a different version of a file - for example with
git checkout <commit> <filename>orgit checkout <filename>
Common Usage
Options
-b <new-branch>
-b <new-branch>
Create a new branch and check it out.If you specify a start point, the new branch will be based on that commit:
-B <branch>
-B <branch>
Similar to
-b, but if the branch already exists, reset it to the start point.-d, --detach
-d, --detach
Check out a commit for inspection and discardable experiments. This puts you in “detached HEAD” state.
-f, --force
-f, --force
When switching branches, proceed even if the index or working tree differs from HEAD. This will discard local changes.
-m, --merge
-m, --merge
When switching branches, if you have local modifications, perform a three-way merge between the current branch, your working tree, and the new branch.
--ours / --theirs
--ours / --theirs
When checking out paths from the index, check out stage #2 (ours) or #3 (theirs) for unmerged paths.
During
git rebase and git pull --rebase, ours and theirs are swapped:--oursgives the version from the branch being rebased onto--theirsgives the version from your branch being rebased
-p, --patch
-p, --patch
Interactively select hunks in the difference to apply in reverse to the working tree.This allows you to selectively discard edits from your current working tree.
-q, --quiet
-q, --quiet
Suppress feedback messages.
-t, --track
-t, --track
When creating a new branch, set up upstream tracking configuration.
--orphan <new-branch>
--orphan <new-branch>
Create a new orphan branch with no parent commits, starting from the specified start point.This is useful when you want to start a completely new history.
Examples
Working with files
Switching branches with local changes
Creating branches
Detached HEAD
When you checkout a commit that is not the tip of any branch, you enter “detached HEAD” state:HEADpoints directly to a commit, not a branch- New commits you create will not belong to any branch
- When you switch away, these commits may become unreachable
Argument Disambiguation
When you rungit checkout <something>, Git tries to determine whether it’s a branch, commit, or file path.
If there’s ambiguity, use -- to force Git to treat the parameter as a file:
For a clearer interface, consider using:
git switchfor changing branchesgit restorefor restoring files
git checkout.Related Commands
- git switch - Switch to a branch (modern alternative)
- git restore - Restore working tree files (modern alternative)
- git branch - List, create, or delete branches
- git merge - Join two or more development histories
