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.

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.
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:
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 visibleRecovery from that state, keeping the original branch untouched:
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 rescueHEAD~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.
| Command | Moves | Rewrites SHA | Source branch | Best for |
|---|---|---|---|---|
rebase --onto | Replays a range, moves the branch | Yes | Kept and moved | Transplanting a feature onto a new base |
cherry-pick | Copies commits to current branch | Yes | Untouched | Taking two commits out of a branch |
merge | Joins histories | No | Untouched | Shared branches, preserving context |
reset --hard | Moves the branch, discards tips | No (drops) | Moved | Undoing local commits |
switch -c | Creates a ref at HEAD | No | New branch | Rescuing detached commits immediately |
git branch <name> <sha> | Creates a ref anywhere | No | New branch | Rescuing after HEAD moved |
The failure modes of a detached HEAD in practice:
| Situation | What was lost | Recovery |
|---|---|---|
| Committed, still detached | Nothing yet | git switch -c feature/x |
| Switched to another branch after committing | Branch ref | git branch x HEAD@{1} from reflog |
git checkout . after committing | Working tree only | git restore . from the commit |
Ran git gc after moving away | Possibly everything | git fsck --lost-found, then git cat-file |
Pushed HEAD:tmp then deleted the remote branch | Remote ref | git 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:
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:
git switch feature/payments
git rebase --onto main release/1.8
# equivalent, explicit three-argument form:
git rebase --onto main release/1.8 feature/paymentsIf 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:
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 messageThe 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:
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 entrygit 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:
git push --force-with-lease origin feature/payments
git push --force-with-lease=feature/payments:4f2c1a9 origin feature/paymentsNever 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.
# 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-fixesCommon 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. Useswitch -c <name>orbranch <name> <sha>. git rebase --ontowith 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-foundis the last resort, not a guarantee. git gcas 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 listshows 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 toolsSmall utilities that fit Git work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Git guides
All Git guidesGit Push Rejected GH001: Large Files and History Rewrite
The 100 MB limit applies to every blob in the pushed history, so deleting the file does not help. Find the object, rewrite with filter-repo, or migrate to LFS.
Git Tags: Lightweight vs Annotated and SemVer Release Tags
An annotated tag stores the tagger, date, and message; describe and --follow-tags only use those. How v:refname sorting and versionsort.suffix fix pre-release order.
Git Detached HEAD and Non-Fast-Forward Push Rejected
A detached HEAD records commits on no branch, and a rejected push protects commits you do not have. Recover with a branch and reflog; integrate before pushing.
Git detected dubious ownership: Docker, Compose, and CI Fixes
A bind mount keeps the host UID and the container runs as root, so Git stops before reading a single object. Trust the path Git resolves, not the one you mounted.
More in Git
All Git guidesThe guides filed next to this one in Git, in library order.