Git Reference ยท Concepts
Detached HEAD
What a detached HEAD means in Git, how you get into it, why commits made there can be lost, and how to save them with a branch or the reflog.
Normally HEAD is a symbolic reference to a branch: it says "I am on main", and main points at a commit. When you make a commit, the branch moves forward and HEAD follows. In a detached HEAD state, HEAD holds a commit id directly instead of a branch name. You are looking at a specific commit that no branch is following.
That is not an error. It is how you inspect an old version, build a tagged release or test a commit. The danger is only that commits you make while detached are not reachable from any branch, so Git will eventually garbage-collect them if you move away without saving them.
git switch --detach v1.0 # or: git checkout v1.0 git branch --show-current # prints nothing when detached git switch -c rescue # keep the commits by giving them a branch
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
How you get there
git switch --detach <commit>orgit checkout <commit-or-tag>(checkout detaches whenever the target is not a local branch name).- Checking out a remote-tracking branch such as
origin/main. - During a rebase, bisect or cherry-pick sequence, Git detaches HEAD internally while it replays commits.
- Checking out a submodule's recorded commit.
Usage notes
- Looking is safe, committing needs care. Reading, building and testing in this state change nothing. Commits are real but unreferenced.
- Save the work before leaving.
git switch -c name(orgit branch nameafter the fact) attaches a branch to the current commit. Git prints a warning with the id when you switch away from unreferenced commits; copy it. - Find lost commits afterwards.
git reflogrecords every place HEAD has been, and unreferenced commits are kept for at least 30 days by default (gc.reflogExpireUnreachableis 30 days, reachable entries 90). See reflog. - Uncommitted changes carry over when you detach, as long as they do not conflict.
- Pushing from a detached HEAD needs an explicit target, such as
git push origin HEAD:refs/heads/fix. - To stop the warning when you deliberately want a detached checkout, use
git -c advice.detachedHead=false switch --detach .... - Tags are safe anchors. Tag the commit if you want a permanent, named marker instead of a branch.