git checkout
git
Usage
git checkout <branch> | git checkout -b <new> | git checkout -- <file>The old command for both switching branches and restoring files, split into switch and restore in git 2.23; checkout -- <file> erases uncommitted edits for good.
Common flags
| Flag | Meaning |
|---|---|
| -b <new> | create the branch and switch to it |
| -B <new> | create or reset it to the current commit |
| -- <file> | overwrite the file with the staged version, losing your edits |
| --track <remote>/<branch> | start a local branch that follows a remote one |
| --detach | sit on a commit with no branch attached |
| -f | throw away local changes to switch anyway |
Examples
git checkout -b feature/loginbranches off the current commit and moves there
git checkout mainswitches branch, same as git switch main
git checkout -- src/app.tsdiscards uncommitted edits to that file; they are gone
The confusion is that undo has several shapes — moving where a branch points is not the same as adding a commit that reverses it.
How to read this
- Square brackets [ ] mark a part you may leave out.
- An ellipsis … means you can list more than one.
- Flags are case-sensitive — in some commands -r and -R do different things.
Questions
Q. What does git checkout do?
The old command for both switching branches and restoring files, split into switch and restore in git 2.23; checkout -- <file> erases uncommitted edits for good.
Q. How do I type it?
git checkout <branch> | git checkout -b <new> | git checkout -- <file> — square brackets mark the parts you can leave out.
Q. How many flags are worth knowing?
6 are listed here; the full set is in man git. This command sits under git.
Related commands
man page: man git-checkout