FIX · ERROR

"You are in
'detached HEAD' state."

You checked out a commit, a tag or a remote branch instead of a local branch. Git is fine. HEAD just does not point at a branch right now, so new commits have no branch name to live on.

git switch -git switch -cgit refloggit branch

The short answer

not an error
1

Just looking

Done exploring? git switch - takes you back to where you were. Or git switch main.

2

Made commits

Keep them: git switch -c new-branch while you are still here. The commits come along.

3

Already left

Find the commit with git reflog, then git branch rescue COMMIT. Commits are not deleted right away.

Git keeps unreachable commits for a while, so a mistake here can nearly always be recovered. Do not wait weeks, though.

What it looks like

real Git 2.34.1 output

Git prints this advice itself, and it names the two exits. The commit hash will differ in your repository. The behaviour is described in the git switch documentation, under --detach. Newer Git versions can word the note slightly differently.

Pick the fix that fits

what you want
you want to
run
result
Go back, nothing to keep
git switch -
Returns to the branch you were on. Edits you committed while detached stay reachable only through the reflog.
Keep new commits as a branch
git switch -c my-work
Creates a branch at your current commit and switches to it. Nothing is moved or lost.
Left already, want a commit back
git reflog then git branch rescue COMMIT
The reflog lists where HEAD has been. Pick the commit hash, and give it a branch.
Stay on a branch from now on
git switch main
Use git switch with a branch name, not a commit hash or tag, to avoid detaching.

Check it worked

always

Run git status. The first line says On branch NAME when you are attached, and HEAD detached at HASH when you are not. git branch marks the current branch with a star, or shows (HEAD detached at HASH).

When it goes wrong

related messages
error: pathspec 'main' did not match any file(s) known to gitBranch name is wrong or not local yetRun git branch -a to see the real names, then switch again.
error: Your local changes to the following files would be overwritten by checkoutUncommitted work is in the wayCommit it, or park it with git stash, then switch.

Questions people ask

What does detached HEAD mean?

HEAD points straight at a commit instead of at a branch name. Git works normally, but new commits are not on any branch.

How do I get out of detached HEAD?

Run git switch - to go back, or git switch main. To keep commits you made, run git switch -c new-branch first.

Did I lose my commits in detached HEAD?

Not right away. git reflog shows where HEAD has been, and git branch NAME COMMIT gives a commit a branch again.

Why did I end up detached?

Usually from checking out a commit hash, a tag, or a remote branch such as origin/main, instead of a local branch.

Git, Visually · Parts 1 to 3 · English