[Git] Error: fatal: you are not currently on a branch — Detached HEAD state explained — How to Fix It
Summary
fatal: you are not currently on a branch appears when you try to commit or merge while Git’s HEAD pointer is detached — meaning it’s referencing a specific commit rather than a branch. In this state, new commits aren’t tied to any branch and can be lost if not attached properly.
Context
Git uses the HEAD pointer to track which branch or commit you’re currently working on. Normally, HEAD points to the latest commit of your active branch (e.g., main). When detached, HEAD points directly to a commit hash, so you’re operating outside of any branch context.
Probable Cause
- Checked out a commit directly (e.g.,
git checkout abc1234). - Switched to a tag or commit instead of a branch.
- Used
git bisectorgit rebaseand exited mid-process. - Manually detached HEAD to inspect history without creating a branch.
Quick Fix
- Check your state:
git statusIf you see
HEAD detached at <commit-hash>, you’re detached. - To keep current work, create a branch from this point:
git switch -c new-branch-name - Now commit safely:
git add . git commit -m "Commit from detached state" - If you were only exploring, return to your branch:
git switch main
Example
# Detached accidentally
$ git checkout 91ab3e7
Note: switching to '91ab3e7'.
# Make changes
$ echo "fix" > file.txt
$ git commit -am "Hotfix while detached"
fatal: you are not currently on a branch
# Fix by creating branch
$ git switch -c hotfix
Switched to a new branch 'hotfix'
$ git commit -am "Hotfix while detached"
[hotfix 2a1b3d4] Hotfix while detached
Alternate Scenarios
- While bisecting: HEAD becomes detached automatically — don’t commit until bisecting ends.
- During rebase or cherry-pick: Detached HEAD is normal — Git reattaches it at the end.
- While viewing old commits: Safe as long as you don’t make commits before switching back.
Pitfalls & Debug
- Symptom → You committed while detached.
Fix → Recover by creating a branch from that commit:
git switch -c rescue-branch <commit-hash> - Symptom → Unsure if detached.
Fix → Run
git rev-parse --abbrev-ref HEAD— if it printsHEAD, you’re detached. - Symptom → Detached during rebase.
Fix → Complete it with
git rebase --continueor abort withgit rebase --abort.
Verification & Next Steps
# Confirm branch attachment
git branch
# Show current reference
git rev-parse --abbrev-ref HEAD
# Inspect detached commits
git log --oneline -n 5
Best Practices
- Always create a new branch before committing in detached mode.
- Use detached HEAD only for exploration or temporary testing.
- Recover commits promptly if you forget to branch before leaving detached state.
- Avoid using commit hashes directly unless you understand the implications.
Sources
Git Documentation — git checkout
Git Documentation — git switch
Stack Overflow — saving detached HEAD state
Tool/Git, OS/Cross-platform, Topic/Branch & HEAD Management