‹ All Git Interview Questions questions

Git Interview Question 10: Detached Head Commits

Git Interview Questions · Test 1 · question 10 of 10

Branches & HEADmedium

To reproduce a customer bug, you ran git checkout v2.0, where v2.0 is a release tag. Git warned that you are in "detached HEAD" state. You ignored the warning and made two commits with a hotfix. You haven't checked out anything else since.

You want to keep those two commits and continue working on them, without moving or recreating any existing branch or tag. What should you do?

Select one answer
Show answer and explanation

Answer:

  • D. Run git switch -c hotfix/2.0.1 while you are still on your latest commit

In detached HEAD state, HEAD points directly at a commit instead of at a branch. New commits still work, but no branch refers to them. If you switch away, nothing references them anymore, and routine garbage collection eventually deletes them. The git-checkout docs say that while you are still on the commit, creating a reference keeps it: git checkout -b / git switch -c, git branch, or git tag. git switch -c hotfix/2.0.1 does this and also attaches HEAD to the new branch, so you can keep working.

Option A doesn't help. v2.0 still points at the tagged release commit, not your two new commits. After switching to main, nothing references your hotfix commits, and they're at risk of garbage collection.

Option B misunderstands the stash. It only saves uncommitted changes. Your hotfix is already committed, so the stash has nothing to save, and the commits are still left without a reference.

Option C keeps the commits, but it forcibly moves the existing main branch onto history that starts at v2.0. That breaks the stem's constraint and drops main's later commits from the branch.

Reference: git-checkout (Detached HEAD)

Practice Test 1 ›

Study guides for Git Interview Questions