Git & GitHub
/Beginner
git checkout
Definition
A command used to switch branches or restore working tree files. It updates files in the working directory to match the version stored in that branch.
Explain Like I'm New
The teleporter. You have created a new branch, but you need to travel to it. `git checkout branch-name` instantly rewrites all the files in your VS Code to look exactly like that branch's universe.
Real World Example
You are working on a new feature, but your boss says there is a critical bug on the live site. You run `git checkout main` to teleport back to the stable code, fix the bug, and then checkout your feature branch again.
Common Use Cases
- •Switching between branches
- •Time traveling to old commits
Crucial Command Flags
| Flag / Option | Description |
|---|---|
| -b | Create and immediately switch to a new branch. |
| -f | Force. Throw away local changes and force checkout. |
| -- [file] | Discard local modifications to a specific file. |
Terminal Output
bash / terminal
# Switch to an existing branch
$ git checkout main
# CREATE and SWITCH to a new branch in one command (Extremely common!)
$ git checkout -b feature/shopping-cart
# Teleport back in time to an old commit (Detached HEAD state)
$ git checkout a1b2c3d
# Danger: Discard any unsaved changes made to index.html and revert it to the last commit
$ git checkout -- index.html
Interview Questions
basic
- What shortcut command creates a new branch AND switches to it at the exact same time?
intermediate
- Why did Git introduce `git switch` to replace `git checkout`?