Q9 of 40 · Git

What is HEAD in Git?

GitJuniorgitHEADdetached-headfundamentalsrefs

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 commit
  • HEAD~1 or HEAD^ — one commit back
  • HEAD~3 — three commits back
  • HEAD@{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

Knowing HEAD is a file (not just a concept), the normal branch-attached vs detached-HEAD distinction, and the ~1/~3 relative notation. Detached HEAD is a common source of 'where did my commits go?' confusion.

// COMMON PITFALL

Making commits in detached HEAD state (e.g., after checking out an old commit to investigate a bug) and then switching away without saving them to a branch — the commits are orphaned and appear lost.