Q9 of 40 · Git
What is HEAD in Git?
Short answer
Short answer: HEAD is a file in .git/HEAD that points to the current branch ref, which in turn points to the latest commit on that branch. It moves forward automatically with each commit. Detached HEAD means HEAD points directly to a commit SHA rather than a branch — this happens after git switch <sha> or git checkout <tag>.
Detail
HEAD is Git's concept of "where you are right now". In normal operation:
HEAD → refs/heads/main → abc123 (latest commit on main)
Every git commit moves the branch pointer forward, and HEAD follows.
Detached HEAD: when you check out a specific commit SHA, tag, or the state at a code-review point, HEAD points directly to the SHA — no branch tracks it:
HEAD → def456 (no branch name)
You can still make commits in detached HEAD state, but they're not reachable from any branch. If you switch to another branch, those commits become orphans (findable via git reflog for ~90 days).
Practical uses of HEAD notation:
HEAD— the current commitHEAD~1orHEAD^— one commit backHEAD~3— three commits backHEAD@{2}— where HEAD was 2 moves ago (reflog notation)
Exiting detached HEAD: git switch -c new-branch-name saves your work to a new branch; git switch main discards the detached commits (after verifying you don't need them).
// EXAMPLE
# See where HEAD points
cat .git/HEAD
# ref: refs/heads/main ← normal: pointing to a branch
# After checking out a tag or SHA
git switch --detach v1.2.0
cat .git/HEAD
# defa1234... ← detached: pointing directly to a commit
# See HEAD relative notation in action
git log HEAD~3..HEAD --oneline # last 3 commits
# Exit detached HEAD by creating a branch
git switch -c hotfix/investigate-v1.2.0
# Or discard the detached work and go back
git switch main// WHAT INTERVIEWERS LOOK FOR
// COMMON PITFALL
// Related questions
How do you create a new branch and switch to it?
Git
Your local Git repository is reporting corrupted objects or a detached HEAD you can't escape. How do you diagnose and recover?
Git
Describe the Git object model — blobs, trees, commits, and tags — and explain why this model makes Git operations fast and safe.
Git