What does `git checkout <commit>` do?
The git checkout <commit> command switches the working directory and HEAD to the specified commit, meaning Git loads the state of the project exactly as it was at that commit.
In simpler terms: you "travel back in time" and look at the code at a chosen point in history.
What exactly happens on git checkout <commit>
When you run:
git checkout a1b2c3dGit does three things:
- HEAD starts pointing directly at this commit
- Files in the working directory are replaced with the versions from this commit
- You end up in a detached HEAD state
Diagram:
HEAD → commit a1b2c3d
Important: you are no longer on a branch
Before the command:
HEAD → main → latest commit
After:
HEAD → a specific commit
This is a key point for an interview.
What you can do in this state
In the detached HEAD state you can:
- view the code
- run the project
- analyze a bug
- compare versions
Dangerous:
- making commits without creating a branch (they can easily be lost when switching back)
How to safely continue working
If after checkout you realize you want to edit code:
git switch -c new-branchThis way you:
- create a branch
- "attach" the changes to the history
What git checkout <commit> does NOT do
does not delete commits does not change history does not roll the branch back
It only moves HEAD and the working state.
A common confusion in interviews
"checkout rolls back the project" - incorrect
checkout switches the state,
while rolling back is git reset or git revert.
Short answer for an interview
git checkout <commit>switches HEAD and the working directory to the specified commit. HEAD detaches from the branch (detached HEAD), and we see the state of the project at that commit, without changing history.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.