branching

git checkout

Legacy multipurpose command that switches branches, restores files, or detaches HEAD to a commit. In modern Git (2.23+), prefer 'git switch' for branches and 'git restore' for files.

git checkout <branch> | git checkout [<commit>] -- <path>

Common flags

Flag Purpose
-b <new> Create and switch to a new branch
-B <new> Create/reset the branch to the start point and switch
-- Separator: everything after is treated as file paths
-f / --force Discard local changes when switching
--detach Check out a commit without moving any branch pointer

Examples

git checkout main

Switch to the main branch (use 'switch' in modern Git)

git checkout -b feature/api origin/main

Create a new branch from origin/main and switch

git checkout -- src/app.js

Discard unstaged changes to a file (use 'restore' now)

Gotcha

'git checkout ' silently discards uncommitted changes with no undo; use 'git restore' — it makes the intent explicit and safer.

Related commands

← All Git commands · Git cheat sheet · Git rebase vs merge