Git & GitHub Interview Question #25
What is a detached HEAD state?
Git Fundamentals, Repository, Working Tree, Staging, Commits & Branch Basics Junior Beginner
Quick Interview Answer
A detached HEAD state occurs when HEAD points directly to a specific commit instead of to a branch reference. You can inspect or build the project in this state, and you can even create commits, but those commits are not automatically attached to a named branch.
Detailed Explanation
A detached HEAD state occurs when HEAD points directly to a specific commit instead of to a branch reference. You can inspect or build the project in this state, and you can even create commits, but those commits are not automatically attached to a named branch.
If work created in detached HEAD should be kept, create a branch pointing to it before moving away. Detached HEAD is useful for examining historical commits but should be understood before making lasting changes.
Code Example
git switch --detach <commit-id>
# Keep new work by creating a branch
git switch -c keep-my-work