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
Related commands
git switch
Modern, focused command (Git 2.23+) that only switches branches — no file restoration overloading like checkout. Safer and clearer for everyday branch changes.
git restore
Modern command (Git 2.23+) for restoring working tree files from the index or a commit, or unstaging files. Replaces the confusing file-mode of 'git checkout'.
git branch
Lists, creates, renames, or deletes branches — pointers to commits. Does not switch branches on its own; use switch or checkout for that.
git merge
Joins the history of another branch into the current one, creating a merge commit when histories diverge. Preserves the full branching topology.
git rebase
Replays commits from your branch on top of another base, producing a linear history without merge commits. Powerful for cleaning up history before pushing.