How do you move to a specific commit?
You can move to a specific commit in Git in several ways, but the idea is the same: you tell Git which commit to make the project's current state.
Let's go through the most important options, the ones you're asked about at an interview.
1. Moving by commit hash (the classic way)
The most direct way is to specify the commit hash:
git checkout a1b2c3dor (the modern variant):
git switch --detach a1b2c3dWhat happens:
- Git loads the project's state from that commit
- you end up in a detached HEAD state
Important to say at an interview:
With this kind of move we are not on a branch, we are just looking at an old version.
2. Moving relative to HEAD
You can move relative to the current commit:
git checkout HEAD~1This means:
HEAD~1- one commit backHEAD~2- two commits back
There is also:
git checkout HEAD^^ is the first parent of the commit (relevant for a merge).
3. Moving while creating a branch (the safe option)
If you want to not just look, but continue working:
git switch -c fix-bug a1b2c3dThis way you:
- move to the commit you need
- create a new branch
- avoid problems with detached HEAD
4. Via a branch or a tag
If the commit is tagged:
git checkout v1.2.0This is often used:
- for releases
- for stable versions
Important point for an interview
git checkout and git switch do not change the history, they just move HEAD.
If you need to roll back the history, that is already:
git resetgit revert
Short answer for an interview
You can move to a specific commit with
git checkout <hash>orgit switch --detach <hash>. HEAD then points directly to the commit and a detached HEAD state occurs. To continue working, it is better to create a new branch.
A common mistake
"To go back to a commit, you need reset"
Looking - checkout / switch,
changing history - reset or revert.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.