Git Checkout
Last updated
git checkout is the classic command for moving around your repository - switching branches, creating a branch with -b, checking out a specific commit, or restoring a file. It does a lot, which is why newer Git split its jobs into git switch (branches) and git restore (files). Both styles still work.
Try these in the terminal playground - a real shell in your browser, nothing to install.
Syntax
| Command | What it does |
|---|---|
git checkout main | Switch to an existing branch |
git checkout -b feature | Create a new branch and switch to it |
git checkout <hash> | Check out a specific commit (detached HEAD) |
git checkout -- file.txt | Discard changes to a file (restore it) |
git checkout main -- file.txt | Restore one file from another branch |
checkout vs switch vs restore
| Task | Old (checkout) | Modern |
|---|---|---|
| Switch branch | git checkout main | git switch main |
| Create + switch | git checkout -b x | git switch -c x |
| Discard file changes | git checkout -- f | git restore f |
Git checkout FAQ
What does git checkout do?
It moves you around the repository. Most often it switches branches (
git checkout main), but it can also create a branch (-b), check out a specific commit, or restore a file to a previous version. Because it does several different jobs, modern Git introduced git switch and git restore to split them up.What's the difference between git checkout and git switch?
git switch is a newer, focused command that only switches (and with -c, creates) branches - clearer and harder to misuse. git checkout does that plus restoring files and checking out commits. For branch work, git switch main and git checkout main are equivalent; use whichever your team prefers.How do I check out a specific commit?
Run
git checkout <hash>. This puts you in a "detached HEAD" state - you're viewing that commit but not on any branch. To keep work from there, create a branch: git switch -c newbranch. To return, check out a branch again with git switch main.How do I discard changes to a file with checkout?
Run
git checkout -- file.txt to throw away uncommitted changes to that file and restore the last committed version. In modern Git the clearer equivalent is git restore file.txt. Both discard your edits, so be sure you don't need them.Can I practice this online?
Yes. Open the terminal playground to run
git checkout in a real shell in your browser - nothing to install. Coddy's free interactive Git course also covers branching and switching step by step.