Git checkout: switch branches or restore files
git checkout is the legacy command for switching branches, creating branches and restoring files. Now replaced by switch and restore, it remains widely used.
What is git checkout?
git checkout is Git's Swiss Army knife: it switches branches, creates branches, and restores files. It's the most versatile but also the most confusing command.
Since Git 2.23, it has been replaced by two clearer commands: git switch for branches and git restore for files.
Git checkout syntax
git checkout branchSwitch to an existing branch
git checkout -b new-branchCreate and switch to a new branch
git checkout -- fileRestore a file from the last commit
Git checkout in practice
Switch branches or restore files.
Branches
Files and commits
checkout vs switch vs restore
checkout
Does everything: branches, files, commits. Versatile but confusing.
switch
Only for switching branches. Clearer and safer.
restore
Only for restoring files. Replaces checkout -- file.
Common mistakes with git checkout
Ending up in detached HEAD
If you checkout a commit instead of a branch, you're in detached HEAD. Create a branch with git checkout -b my-branch to avoid losing your work.
Overwriting local changes
git checkout -- file overwrites uncommitted changes to the file. This is irreversible if the changes were not stashed or committed.
Confusing branch and file
If a branch and a file have the same name, use -- to disambiguate: git checkout -- file.
Part of the Git Branching Workflow guide
GitQuest is created by Anaïs (nouvelle fenêtre), web developer and head of education, specializing in tech training and digital accessibility.
Questions about git checkout
Navigate between branches with GitQuest
Learn to juggle between branches and commits through interactive challenges.
Start the investigations