Git checkout vs. switch: clearer branch commands
Compare checkout’s multi-purpose behavior with switch for branch navigation and restore for file recovery, including compatibility considerations.
git checkout can switch branches, create branches, detach HEAD, and restore paths. That flexibility makes some commands ambiguous. git switch focuses on branch movement, while git restore focuses on files and the index.
Branch work: prefer switch for clarity
git switch main
git switch -c feature/example
The older equivalents are git checkout main and git checkout -b feature/example. Existing scripts may use checkout for compatibility, but interactive documentation is often clearer with switch.
File recovery: use restore deliberately
git restore path/to/file
git restore --staged path/to/file
The first replaces unstaged changes in the named tracked file with the index version. The second removes the file from the index while preserving its working-tree content.
Risk:
git checkout -- .andgit restore .can discard uncommitted tracked-file changes across the current directory. Inspectgit diffand back up valuable work first.
Detached HEAD is still available
git switch --detach <commit>
This is useful for inspection. Commits made while detached are easy to lose track of, so create a named branch before doing work you want to keep.
Use switch and restore when your installed Git supports them and the clearer intent helps. Checkout remains valid and useful, especially in older environments and established automation. See the branching cheat sheet for a complete flow.