How to Fix Git Detached HEAD State Error
In this tutorial, you'll learn about How to Fix Git Detached HEAD State Error. We cover key concepts, practical examples, and best practices.
You see HEAD detached at <commit> — you checked out a specific commit instead of a branch, and any new commits will not belong to any branch.
The Problem
git checkout abc123
Shows:
Note: switching to 'abc123'.
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.
Step-by-Step Fix
Step 1: Attach HEAD to a branch
If you only want to look around and have not made changes:
# Return to main branch
git checkout main
Step 2: Create a branch from the detached state
If you made commits and want to keep them:
# Create and switch to a new branch at the current position
git switch -c new-branch-name
Or:
git checkout -b new-branch-name
Step 3: Keep the detached commits
If you have made commits in detached HEAD state, find them:
git reflog
Create a branch to preserve them:
git branch my-feature <commit-hash>
Step 4: Cherry-pick detached commits to a branch
If you want specific commits on an existing branch:
# While on the target branch
git cherry-pick <detached-commit-hash>
Step 5: Prevent accidental detached HEAD
# Instead of checking out a commit hash, check out a branch
git checkout <branchname>
# To check out a remote branch
git checkout --track origin/<branchname>
Prevention Tips
- Always check out branch names, not commit hashes
- Use
git switchinstead ofgit checkout(clearer semantics) - If you need to inspect an old commit, use
git show <commit>orgit log -p <commit> - Create a branch immediately if you need to make changes
- Use
git worktreefor working on multiple branches simultaneously
Common Mistakes with detached head
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
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