Git & GitHub Course
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 / OptionDescription
-bCreate and immediately switch to a new branch.
-fForce. 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`?

Flash Cards

Question

Shortcut command?

Click to reveal answer
Answer

`git checkout -b new-branch-name` (The -b stands for branch).

Question

Why replace?

Click to reveal answer
Answer

Because `git checkout` does too many things. It can switch branches, but it can ALSO overwrite and delete uncommitted files (e.g., `git checkout -- file.txt`). This dual-purpose was highly confusing for beginners.