Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

git rebase --onto vs cherry-pick: Recovering a Detached HEAD

Commits made on a detached HEAD belong to no branch. Rescue them from the reflog, then transplant them with rebase --onto or copy them with cherry-pick.

~5 min readGit
#Git#Rebase#Branching#Debugging
3D illustration of a chain of linked commit cubes with one cube floating detached above it

Introduction & Quick Summary

Symptom. You checked out a tag or a remote commit, made a few commits, and now git push answers fatal: You are not currently on a branch. To push the history leading to the current (detached HEAD) state now, use git push origin HEAD:<name-of-remote-branch>. In a worse version, you already ran git switch main: the work is gone from git log and only git reflog can still see it.

Cause. git checkout <sha>, git switch --detach, and git checkout v1.9.0 all move HEAD to a commit instead of a branch. Commits made in that state belong to no branch, so they are reachable only from HEAD and the reflog. The moment HEAD moves — a switch, a reset, another checkout — those commits become unreachable and are eventually pruned by git gc after gc.reflogExpireUnreachable (30 days by default, 90 for the reflog entry itself).

Fix. Two commands cover almost every case. If HEAD is still on the detached commits: git switch -c rescue. If you have already moved away: git reflog, find the commit, and git branch rescue <sha>. After that, transplant the work where it belongs with git rebase --onto <newbase> <oldbase> rescue, or copy individual commits with git cherry-pick <range>; the choice depends on whether you want the branch pointer moved or a few commits copied.

Core Mechanics, Signatures & Reproducible Setup

The three commands that get confused here move different things.

code
git rebase --onto <newbase> <upstream> [<branch>] git cherry-pick <commit>… # or <A>..<B> / <A>^..<B> git reset --hard <commit>

rebase --onto replays every commit in the half-open range (upstream, branch] on top of newbase, then moves branch to the result. The two-argument form git rebase <upstream> is shorthand for --onto <upstream> <upstream>. cherry-pick copies the named commits onto the current branch, does not touch the source branch, and creates commits with new SHAs. Neither restores anything by itself, because both rewrite history.

A reproducible detached-HEAD accident, six commands:

bash
git clone https://github.com/example/repo.git && cd repo git switch --detach HEAD~3 # HEAD now names a commit, not a branch echo "hotfix" >> app.txt && git commit -am "hotfix: guard null token" git switch main # the two commits are now only in the reflog git log --oneline -3 # does not show them git reflog | head -5 # 'commit: hotfix: guard null token' is visible

Recovery from that state, keeping the original branch untouched:

bash
git branch rescue HEAD@{1} # or the exact SHA printed by git reflog git log --oneline main..rescue # confirm only your commits are in the range git rebase --onto main HEAD~3 rescue

HEAD~3 in the last line is the old base: the commit the detached work started from. Get it from git merge-base main rescue when you are unsure, because rebasing with the wrong upstream replays commits that already exist on main and produces conflicts that make no sense.

Key Comparison Table

Which history-rewriting tool to reach for depends on what you want to keep.

CommandMovesRewrites SHASource branchBest for
rebase --ontoReplays a range, moves the branchYesKept and movedTransplanting a feature onto a new base
cherry-pickCopies commits to current branchYesUntouchedTaking two commits out of a branch
mergeJoins historiesNoUntouchedShared branches, preserving context
reset --hardMoves the branch, discards tipsNo (drops)MovedUndoing local commits
switch -cCreates a ref at HEADNoNew branchRescuing detached commits immediately
git branch <name> <sha>Creates a ref anywhereNoNew branchRescuing after HEAD moved

The failure modes of a detached HEAD in practice:

SituationWhat was lostRecovery
Committed, still detachedNothing yetgit switch -c feature/x
Switched to another branch after committingBranch refgit branch x HEAD@{1} from reflog
git checkout . after committingWorking tree onlygit restore . from the commit
Ran git gc after moving awayPossibly everythinggit fsck --lost-found, then git cat-file
Pushed HEAD:tmp then deleted the remote branchRemote refgit fetch origin tmp before GitHub prunes it

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Rescue before anything else

The fastest correct action when you notice the detached state is to give the commit a name. Do this before investigating:

bash
git switch -c rescue-detached # keeps every commit reachable git status # confirms a branch name, not 'HEAD detached'

Everything else — rebasing, cherry-picking, force-pushing — can wait, because a branch ref makes the commits part of normal history.

2. Transplanting a feature onto a new base

--onto is the only tool that answers "this branch was built on the wrong base". Replaying feature/payments from release/1.8 onto main:

bash
git switch feature/payments git rebase --onto main release/1.8 # equivalent, explicit three-argument form: git rebase --onto main release/1.8 feature/payments

If the rebase conflicts on a commit that already landed on main through a squash merge, git rebase --onto with the merge-base of the two branches avoids the duplicates: git rebase --onto main $(git merge-base main feature/payments) feature/payments.

3. Copying a range instead of moving a branch

cherry-pick is right when the source branch must stay as it is — for example, backporting two fixes from main into a release branch:

bash
git switch release/1.8 git cherry-pick 4f2c1a9^..b7d0e31 # both endpoints inclusive git cherry-pick -x 4f2c1a9^..b7d0e31 # adds '(cherry picked from …)' to the message

The range syntax is the trap: A..B excludes A, A^..B includes it. -x records the source SHA, which is the only durable link between the copy and the original once both branches have moved on.

4. Undoing a rebase that went wrong

Rebase is recoverable for as long as the reflog survives. ORIG_HEAD is written by rebase and merge, so the previous tip is one command away:

bash
git reflog | grep -i rebase # 'rebase (start)' and 'rebase (finish)' entries git reset --hard ORIG_HEAD # when ORIG_HEAD still points at the pre-rebase tip git reset --hard HEAD@{5} # or the exact reflog entry

git rebase --abort only works while a rebase is in progress. After it finishes, recovery is reset --hard to a reflog entry; nothing in the working tree can tell you which entry, so read the log's timestamps.

5. Sharing a rewritten branch safely

A rebased branch has new SHAs, so a normal push is rejected. --force-with-lease refuses to overwrite if someone else pushed in the meantime, which is the difference between a deliberate rewrite and losing a colleague's commit:

bash
git push --force-with-lease origin feature/payments git push --force-with-lease=feature/payments:4f2c1a9 origin feature/payments

Never force-push main or a release branch. If the commits are already reviewed, prefer git revert and a new commit; revert is safe on shared history because it adds instead of rewriting.

6. Detached HEAD inside CI and submodules

CI checkouts of a pull request are detached by design, and a script that runs git commit there silently creates commits nobody can find. Submodules behave the same way: git submodule update --init leaves each submodule at a detached commit pinned by the parent repository, which is correct but confuses a git pull inside the submodule.

bash
# in CI: name the branch before committing git switch -c ci/${CI_COMMIT_REF_SLUG:-build} # in a submodule: move to a real branch before editing git -C vendor/lib switch -c local-fixes

Common Compilation/Runtime Mistakes & Version Gotchas

  • Using git checkout - as a rescue. It switches to the previous branch and immediately detaches you from the commits again. Use switch -c <name> or branch <name> <sha>.
  • git rebase --onto with swapped arguments. The first argument is the new base and the second is the old base; reversing them replays the wrong range and usually conflicts on unrelated files.
  • Assuming a reflog is permanent. Entries expire after 90 days and unreachable commits are pruned after 30 by gc.reflogExpireUnreachable. A month-old orphan branch is often gone; git fsck --lost-found is the last resort, not a guarantee.
  • git gc as routine maintenance on a workstation. It prunes unreachable objects, including a detached commit you meant to recover tomorrow.
  • Cherry-picking a merge commit. Without -m 1, git refuses; with the wrong parent number, the copy contains the wrong side of the merge.
  • Rebasing a branch others pulled. Reviewers' clones keep the old SHAs, and the next fetch looks like duplicated work. Force-with-lease after coordinating, or revert instead.
  • Worktrees share the reflog entry point, not the branch. A commit made in a linked worktree is in that worktree's HEAD; git worktree list shows where to look before assuming the commit is lost.

Related tools. Compare the recovered branch against main with the text diff tool before rewriting anything, so the change you are about to replay is exactly the change you reviewed; when a commit message or a payload in the diff contains escaped JSON, the JSON formatter turns it back into something readable.

Try matching browser tools

All tools

Small utilities that fit Git work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Git guides

More in Git

All Git guides

The guides filed next to this one in Git, in library order.