Git Detached HEAD — How to Save Changes Fix
In this tutorial, you'll learn about Git Detached HEAD. We cover key concepts, practical examples, and best practices.
A detached HEAD means git's HEAD pointer references a specific commit instead of a branch. Work done in this state is not associated with any branch, and switching away can make it seem like the changes have vanished.
The Problem
git checkout v1.0
Git warns:
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.
You make changes, commit, then switch to main:
git checkout main
Now your commits are gone.
Wrong Approach
# WRONG — switching away without creating a branch
git commit -m "important work"
git checkout main # Commits are now orphaned
Right Approach
# Create a branch from the current HEAD
git checkout -b my-feature-branch
Expected output:
Switched to a new branch 'my-feature-branch'
Now your commits are safe. You can commit normally:
git add .
git commit -m "important work"
Step-by-Step Fix
Step 1: Recognize detached HEAD
git status
Shows:
HEAD detached at v1.0
Step 2: Create a branch immediately
git checkout -b temp-branch
Step 3: Recover orphaned commits (if already switched away)
git reflog
Find the commit hash:
abc123 HEAD@{0}: checkout: moving from v1.0 to main
def456 HEAD@{1}: commit: important work
Step 4: Create a branch at the orphaned commit
git branch recovery-branch def456
Step 5: Verify your changes are there
git checkout recovery-branch
git log --oneline -5
Step 6: Merge the recovered branch
git checkout main
git merge recovery-branch
Step 7: Clean up temporary branches
git branch -d temp-branch recovery-branch
Prevention Tips
- Always create a branch immediately when you enter detached HEAD
- Use
git stashfor temporary experiments - Use
git checkout -binstead of baregit checkout <commit> - Run
git statusbefore switching branches to check for detached HEAD - Know the reflog is your safety net — it tracks every HEAD change for 90 days
Common Mistakes with detached head fix
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world GIT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro