Software

Git Detached HEAD Explained: How to Recover Lost Commits and Get Back to a Branch

Talha Aslan 19 min read

Short answer

What is a git detached head?

A git detached head means HEAD points directly at a specific commit instead of at a branch. You can still commit in this state, but those commits belong to no branch. If you switch away and nothing else references them, Git's garbage collection may eventually delete them. The fix is to create a branch before you leave.

Keep reading for the full details and examples

If your terminal suddenly shows a line like "HEAD detached at" and your latest commits seem to vanish, take a breath. A git detached head is not an error. It is a normal Git state, and one command usually fixes it. This guide explains how the state happens, how to get back to a branch when you made no commits, how to keep commits you made while detached, and how to recover lost commits with reflog after you switched away.

The DETACHED HEAD section of the official git checkout documentation puts it plainly: HEAD normally refers to a branch, and the branch refers to a commit. When detached, the branch layer drops out and HEAD refers to the commit directly.

If you are worried right now, do this first:

  1. Run git status and read the first line.
  2. If you are detached and made commits, run git switch -c rescue before you go anywhere else.
  3. Made no commits? Run git switch main, or use the name of your working branch.
  4. If you already switched away and lost commits, check the output of git reflog.

What does HEAD normally point to?

In Git, HEAD answers the question "where am I right now?" In normal work, HEAD holds the name of a branch, for example main. In turn, main points at the latest commit on that branch. When you commit, Git moves main to the new commit, and because HEAD still points at main, you move forward too.

Here is the picture in words. In the normal state, HEAD points at main, main points at commit C, C's parent is B, and B's parent is A. When new commit D arrives, main moves to D and HEAD stays on main.

In the detached state, the branch link disappears from the chain. For example, if you check out commit B directly, HEAD now points at B while main stays at D. If you then create commit E, its parent is B, but only HEAD points at E. Therefore, once HEAD moves elsewhere, the path to E disappears too.

Once you see this structure, a git detached head stops feeling scary. The state itself is harmless; the risk is that work created in it has no name.

How do you end up in a git detached head state?

Most people land here without meaning to. Git enters this state whenever you check out something other than a branch name. The common paths are:

  • Checking out a commit hash directly, for example git checkout a1b2c3d.
  • Checking out a tag, for example git checkout v2.0. Tags are not branches; they point at a fixed commit.
  • Checking out a remote tracking branch directly, for example git checkout origin/main.
  • Using a relative reference, for example git checkout HEAD~3 or master^^.
  • Asking for it on purpose with git switch --detach.
  • Being in the middle of a rebase; while Git replays commits one by one, HEAD temporarily points at commits.
  • Updating a submodule, which we cover separately below.

The first four are where beginners trip most often. Checking out origin/main is especially confusing, because it feels like "switching to the remote main." In fact, it is not a branch at all; it is a read only snapshot of the remote as of your last fetch.

How can you tell that you are in detached HEAD?

Git shows the state clearly in several places. However, your terminal theme or editor may hide it, so a command is the safest check.

  • git status reports on its first line that HEAD is detached and at which commit, instead of naming a branch.
  • In git branch, the starred line shows a detached HEAD note in parentheses instead of a branch name.
  • git rev-parse --abbrev-ref HEAD returns just HEAD instead of a branch name, which is handy in scripts.
  • Many shell prompts and editors show a short commit hash instead of a branch name.

For example, if the VS Code status bar shows a seven character hash where the branch name usually sits, you are probably detached. In that case, confirm with git status and pick the next step.

The exact wording of Git's warning can change between versions. For that reason we don't quote the on screen message verbatim here; the meaning stays the same: HEAD is attached to a commit, not a branch.

Which command should you use in which situation?

The right command depends on two questions: did you commit while detached, and are you still on that commit? The decision table below covers the common scenarios.

SituationRiskRecommended command
You only looked at an old version, no commitsNonegit switch main or git switch -
You committed and are still detachedSwitching away orphans the commitsgit switch -c new-branch
You committed and want to stay detachedLow once a reference existsgit branch new-branch or git tag name
You committed and already switched awayOrphaned commits await garbage collectiongit reflog, then branch from the hash
You are mid rebaseUnfinished operationgit rebase --continue or --abort
A submodule looks detachedUsually normalCreate a branch in the submodule before editing

Each row has its own section below. Find your row and jump there.

How do you get back to a branch if you made no commits?

This is the easy case. If you detached to inspect an old version or test a bug and made no new commits, you have nothing to lose. You simply switch back to your working branch.

  1. First, run git status to check for uncommitted changes.
  2. If the tree is clean, run git switch main, or use your branch name.
  3. If you don't remember the previous branch, use git switch -.
  4. Confirm with git status that you are on a branch again.

The official git switch documentation notes that a dash stands for the previous location and that people often use it to undo a switch made by mistake. So you don't need to remember where you were.

If you have uncommitted changes worth keeping, the safest route is to create a branch and commit first. Also, Git warns you during the switch rather than silently overwriting files that would conflict.

How do you keep commits you made while still detached?

If you committed while detached and have not moved yet, you are at the perfect moment to save the work. The official git checkout documentation lists three options for this point.

  • git switch -c new-branch, or its equivalent git checkout -b new-branch, creates a branch at the current commit and attaches HEAD to it. You leave the detached state.
  • git branch new-branch creates the branch but leaves HEAD detached.
  • git tag tag-name marks the commit with a tag, and HEAD stays detached.

In most cases the first option is the right one, because it creates a reference and returns you to normal work at once. The second and third options make sense if you want to keep experimenting in the detached state.

Choose a meaningful branch name. For example, "payment-bug-experiment" beats "test" when you look at it two weeks later. Next, we cover how to bring that branch into your main line.

How do you recover lost commits with reflog after switching branches?

This is the scenario people search for most: you committed while detached, ran git switch main, and the commits disappeared from the log. The good news is that they still exist; nothing names them anymore. The official documentation says to recover the object name first, typically with git reflog, and then create a reference to it.

  1. Run git reflog. It lists every position HEAD visited, newest first.
  2. Find the line just before the switch to your branch; your commit message appears there.
  3. Copy the short hash at the start of that line.
  4. Run git switch -c recovered-work HASH to create a branch at that commit.
  5. Verify with git log --oneline that your commits are back.

Also, if you only want the last few moves, the documentation gives short queries such as git reflog -2 HEAD or git log -g -2 HEAD. That keeps you from getting lost in a long list.

In the reflog you will also see expressions like HEAD@{2}. That means "where HEAD was two moves ago," and you can use it in place of a hash. Still, the number shifts with every new move, so working with the copied hash is safer.

What is reflog, and how long does it keep commits?

The reflog records when branch tips and other references changed in your local repository. According to the official git reflog documentation, HEAD's reflog also records branch switching. That is why your exit from the detached state shows up there right away.

The documentation defines two config keys for pruning old entries. It gives a default of 90 days for gc.reflogExpire and 30 days for gc.reflogExpireUnreachable, which covers entries no longer reachable. Commits left behind by a detached HEAD usually fall into the second group. However, configuration can change both values, so check the current value in your repository with git config and in the official docs.

Two limits matter. First, the reflog is local; a clone on another machine does not see your moves. Second, even with a reflog entry, garbage collection can eventually clean up the objects. So instead of relying on "the reflog has it," recover right away.

In short, the reflog is not a backup system. It is a safety net for the recent past. A real backup means putting your work on a branch and pushing it to a remote.

How do you bring recovered commits into your main branch?

Once your commits sit on a branch, you usually want them in a main line such as main. There are a few common ways, and the right one depends on how your team treats history.

  • Merge: run git switch main, then git merge recovered-work. History stays exactly as it happened.
  • Move a single commit: run git switch main, then git cherry-pick HASH. Git applies only the change from the commit you pick.
  • Rebase: replay the recovered branch on top of main for a linear history.

Our article on git rebase vs merge walks through when each choice fits. If a conflict appears during the merge, our guide on how to resolve git merge conflicts takes you through it step by step.

After the move, delete the temporary branch with git branch -d recovered-work. The lowercase d makes Git warn you if the branch is not merged yet, which acts as a second lock against losing work by accident.

Is a git detached head normal during a rebase?

Yes. A rebase replays your commits one by one onto a new base. While it runs, Git temporarily attaches HEAD to commits until the operation ends. In this situation git status also tells you that a rebase is in progress.

What you need to do is finish or cancel the rebase, not "fix" the detached HEAD. According to the official git rebase documentation, git rebase --continue restarts the process after you resolve a conflict, while git rebase --abort cancels it and resets HEAD to the original branch.

A common mistake is to panic mid rebase and try something like git switch main. That stacks a new operation on top of an unfinished one. First run git status to see where you are, then decide whether to continue or abort.

We cover rebase itself, and its risks on shared branches, in our rebase and merge comparison. Here we only explain how it relates to a detached HEAD.

Why do submodules end up in detached HEAD on their own?

In projects with submodules, you meet a detached HEAD almost daily, and that is by design. According to the official git submodule documentation, the default update procedure is checkout, which checks out the commit recorded in the superproject on a detached HEAD in the submodule.

The logic is simple: the superproject says "this submodule at this commit," not a branch name. As a result, everyone gets the same version. So a detached HEAD in a submodule is not a problem by itself.

The trouble starts when you edit files inside the submodule and commit. That commit also belongs to no branch and can drop out of sight at the next update. So before you work in a submodule, enter its folder, create a branch with git switch -c branch-name, and then make changes.

The documentation also notes that with the merge and rebase update procedures, the submodule HEAD does not detach. For general submodule usage, see our guide on what a git submodule is and how to use it.

Why do CI/CD pipelines run in detached HEAD?

Many continuous integration systems fetch the exact commit that triggered a build and check it out directly. As a result, the build script may run on a detached HEAD rather than a branch. How each system behaves depends on its own documentation, so check the docs for your CI tool.

This has a practical consequence. If your script reads the branch name with git rev-parse --abbrev-ref HEAD, a detached checkout returns only HEAD, and the script may make the wrong decision. For example, a "deploy if on main" rule never fires.

Therefore, in CI scripts, read the branch from the variables your CI system provides instead of from Git's current state. Also, if a script commits and pushes back from CI, make sure it switches to a branch explicitly first.

For the core ideas behind pipelines, read our article on what CI/CD is.

Can you push while in a detached HEAD state?

Yes, but carefully. If you run plain git push while detached, Git cannot tell which remote branch you mean, because your current position has no branch name. So the command usually stops with an error or a warning.

The cleanest route is to create a local branch first and push that. In other words, run git switch -c new-branch, then git push -u origin new-branch. That gives you a named reference both locally and on the remote.

Git also offers an explicit refspec that pushes HEAD straight to a remote branch name, for example git push origin HEAD:refs/heads/new-branch. However, this does not create a local branch, and you stay detached. Outside one off scripts, creating the local branch first is the clearer habit.

One warning: never force push from a detached HEAD over an existing remote branch. For instance, pushing an old commit in place of main can wipe out your teammates' work. If you are unsure, use a new branch name and merge through your normal review process.

Why are you left in detached HEAD after git bisect?

git bisect runs a binary search through history to find the commit that introduced a bug. At each step, Git checks out a commit in the middle of the range. Those commits are not branch tips, so you work in detached HEAD for the whole search. That is expected.

When the search ends, run git bisect reset. It takes you back to the branch where you started. Many people forget this step, open the terminal the next day, find themselves detached, and can't remember why.

If you try a fix during bisect, the same rule applies: create a branch before you make it permanent. Otherwise, after the reset, the only path to that attempt lives in the reflog.

Also, during a long bisect session, note which commits you marked good or bad. If the search gets interrupted, the note helps you resume, and it shows teammates the exact range you searched. In short, bisect is one of the best uses of a detached HEAD, as long as you clean up afterward.

Example scenario: fixing a bug on a release tag and losing it

This is an example scenario, not a real person's case. A developer runs git checkout v2.0 to reproduce a bug reported on an older release. They find it, fix it and create two commits. Then they run git switch main to look at the current code. When they check the log, the two commits are gone.

After a moment of panic, they run git reflog. Near the top they see the switch to main, and right below it their own commit message. They copy the hash from that line and run git switch -c v2-bug-fix HASH. Both commits are back.

Next, the team wants the fix on main as well. The developer switches to main and applies only the fix commit with git cherry-pick. Finally, they push the branch to the remote, which removes any reliance on the reflog. In short, the whole recovery takes a few commands, and it works only because they acted before cleanup.

What are the most common mistakes?

Most losses linked to a detached HEAD come from panicked decisions, not from the state itself. Steer clear of these:

  • Committing while detached and switching away without creating a branch.
  • Rewriting the same change from scratch instead of searching for the lost commit.
  • Putting off recovery for days and raising the garbage collection risk.
  • Trying to fix a detached HEAD in the middle of a rebase.
  • Editing a submodule without creating a branch in it.
  • Reaching for hard to undo commands such as git reset --hard during recovery.
  • Checking out origin/main and believing you are working on a branch.

Be especially careful with reset. Used wrongly, it throws away uncommitted changes, so during a recovery it creates a new loss instead of solving the old one. Before you run a command you don't know well, creating a quick branch to pin your position is always safer.

How does git checkout vs git switch affect detached HEAD?

Historically, git checkout is a multi purpose command that both changes branches and restores files. That flexibility means it silently detaches HEAD when you pass a commit hash. In contrast, git switch focuses only on changing branches.

The practical difference: if you pass git switch something that is not a branch, you must ask for the detached state explicitly with --detach. The official git switch documentation describes that option as meant for inspection and discardable experiments. As a result, you are less likely to detach by accident.

Taskgit checkoutgit switch
Switch to a branchgit checkout maingit switch main
Create and switch to a branchgit checkout -b namegit switch -c name
Detach at a commit on purposegit checkout HASHgit switch --detach HASH
Go back to the previous positiongit checkout -git switch -

So making git switch the team habit for branch work reduces detached HEAD confusion. For the rest of the everyday commands, see our Git and GitHub guide to essential commands.

When should you use a detached HEAD on purpose?

A detached HEAD is not a bad thing; in the right place it is very useful. The official documentation also calls it handy for checking out a commit that is not at the tip of a branch, or for creating throwaway commits.

  • Checking out a release tag to see how an old version behaved.
  • Running a binary search through history to find where a bug started.
  • Trying a throwaway experiment and returning without a trace if you don't like it.
  • Reproducing a build on one exact commit.

What these uses share is an expectation that the work won't last. If you produce something worth keeping during the experiment, the rule is simple: create a branch before you leave. That single habit prevents nearly every git detached head loss.

How do you help a teammate stuck in detached HEAD?

When a teammate writes "my commits are gone," the first reflex is often to dictate a command remotely. However, a command in the wrong order can turn a recoverable situation into a permanent loss. So gather facts first, then act.

  1. Ask for the first few lines of git status.
  2. Next, ask them to share the output of git reflog -10.
  3. Find the lost commit message in the reflog together.
  4. Have them run git switch -c rescue HASH with that hash.
  5. Finally, ask them to push the branch and let you know.

Don't rush; a few minutes of waiting deletes nothing. Meanwhile, avoid suggesting reset, clean or force push. Until the recovery finishes, the only goal is to give the lost commit a name. That way you solve the problem and also teach a method your teammate can apply alone next time.

How do you prevent losses from a detached HEAD?

Prevention always costs less than recovery. At Talha Aslan and team, we recommend these habits in development workflows:

  1. Keep the branch name visible in your shell prompt or editor, so you notice a detached state at once.
  2. Use git switch for branch work and detach only on purpose with --detach.
  3. Before committing while detached, create a branch with git switch -c.
  4. Push valuable work to a remote by the end of the day; the reflog is local, the remote is not.
  5. Create a branch in a submodule before you work in it.

If authentication fails when you push, our article on the SSH permission denied (publickey) error can help. If you pushed a secret by mistake, our guide on what to do when an .env file gets committed to Git shows how to clean up the leak. These habits also make open source work smoother; for details, see our beginner guide to contributing to open source on GitHub.

Frequently Asked Questions

What happens if I commit in a git detached head state?
The commit works fine, but it belongs to no branch; only HEAD points at it. If you switch to another branch, no name leads to that commit anymore, and garbage collection may eventually delete it. So create a branch with git switch -c before you leave; the moment you do, the commits have a permanent name.
Can I get back commits I lost after leaving detached HEAD?
Usually yes, as long as cleanup has not run yet. Run git reflog, find your commit message on the line just before the branch switch, and run git switch -c new-branch with that hash. The reflog is local and its retention depends on configuration, so recover promptly and push the branch.
Is a detached HEAD dangerous?
No, not by itself. The official Git documentation describes it as useful for inspecting old versions and making throwaway experiments. The only risk is that commits you make in this state have no name. If you create a branch as soon as you produce something worth keeping, you lose nothing at all.
Does git switch vs git checkout matter for detached HEAD?
Yes. git checkout silently detaches HEAD when you give it a commit hash. git switch, by contrast, requires the --detach option for any target that is not a branch. Using git switch for branch work therefore lowers the chance of detaching by accident and makes your intent visible in the command.
Why do I keep seeing detached HEAD in a submodule?
Because git submodule update, by default, checks out the commit recorded in the superproject on a detached HEAD inside the submodule. That design ensures everyone gets the same version. If you plan to edit files inside the submodule, enter its folder and create a branch first, then start working.
How long does Git keep reflog entries?
According to the official git reflog documentation, gc.reflogExpire defaults to 90 days and gc.reflogExpireUnreachable, for entries no longer reachable, defaults to 30 days. Commits left behind by a detached HEAD usually fall into the second group. Configuration can change these values, so check the current setting with git config.
  • git detached head
  • git reflog
  • git switch
  • git checkout
  • recover lost commits
  • git branch
  • git submodule
Share:
Talha Aslan

Google Partner digital marketing expert. Hands-on with SEO, Google Ads, web design and e-commerce projects since 2012; every post here comes from that experience.

Next project

Get a quote for your project.

Your brief goes straight to Talha Aslan and team: strategy led by Talha, delivery by an experienced team. We reply the same day and send the scope, timeline and price as a written quote within 1 business day.