Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readGit
#Git#Version Control#Recovery#CI
3D illustration of a commit chain with one cube floating detached above it and a rejected push arrow

Introduction & Quick Summary

Symptom. Two Git states that stop a day's work. After checking out a tag, a commit, or a PR ref, Git prints You are in 'detached HEAD' state. … If you want to create a new branch to retain commits you create, you may do so (now or later) by using -c with the switch command. Or a push is refused: ! [rejected] main -> main (non-fast-forward) with error: failed to push some refs … hint: Updates were rejected because the tip of your current branch is behind its remote counterpart.

Cause. Detached HEAD means HEAD points directly at a commit instead of at a branch ref. Anything you commit exists, but no branch records it, so the next git checkout moves HEAD away and the commits become unreachable from any ref. A non-fast-forward rejection means the remote branch has commits your local branch does not: pushing would make the remote lose them, so Git refuses until you integrate your work.

Fix. For a detached HEAD, create a branch before leaving — git switch -c rescue — and recover later work through git reflog. For the rejected push, fetch, inspect the divergence, integrate (git rebase origin/main, or git merge), then push. --force-with-lease is only for the case where you intentionally rewrote history and have confirmed the remote tip is still the one you expect.

Core Mechanics, Signatures & Reproducible Setup

Reproduce both in a scratch repository:

bash
git init demo && cd demo git commit --allow-empty -m "first" git tag v1.0 git checkout v1.0 # detached HEAD: HEAD -> v1.0 commit, no branch echo fix >> file.txt && git add . && git commit -m "hotfix" # commit on no branch git switch main # hotfix is now reachable only through the reflog git reflog # <sha> HEAD@{1}: commit: hotfix git switch -c hotfix-branch <sha> # recover it

And the rejected push:

bash
# clone A pushes a commit; clone B still has the older tip git push origin main # in A: fine git push origin main # in B: rejected, non-fast-forward git fetch origin git log --oneline --graph --decorate HEAD origin/main git rebase origin/main # replay B's work on top of A's commit git push origin main # now fast-forward

The decision at the divergence is the whole task: if your local commits are unpublished work, rebase or merge them onto the remote tip; if the remote commits are the ones you want to discard, that is a rewrite and needs the force family and a reason.

Key Comparison Table

SituationCommandResult
Detached, no new commitsgit switch - or git switch mainBack to a branch, nothing lost
Detached, commits worth keepinggit switch -c rescueBranch at the current commit
Left detached and switched awaygit reflog, then git switch -c rescue <sha>Recover from reflog
Refs gone entirelygit fsck --lost-foundDangling commits in .git/lost-found
Unpublished local commits, remote advancedgit rebase origin/mainLinear history on top of remote
Local commits already pushed, remote advancedgit pull --rebase, then pushClean push
Intentional rewritegit push --force-with-leaseOverwrites only if remote unchanged
Remote is authoritativegit reset --hard origin/mainDiscards local commits
Push rejectionMeaningCorrect response
(non-fast-forward)Remote has commits you lackFetch, rebase, push
(fetch first)Local ref missing entirelygit fetch, then inspect
[remote rejected] … protected branchPolicy blocks direct pushOpen a PR
! [remote rejected] (stale info)Someone else pushed firstgit fetch and retry
GH006: Protected branch update failedBranch protection bypass missingPR flow, not force

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Building from a tag and committing the fix there

Release builds check out a tag, so any hotfix is made detached. Create the branch first; the name is free and the commit becomes reachable:

bash
git checkout v2.3.1 # edit git switch -c hotfix/2.3.1 # branch at the current detached commit git add -A && git commit -m "fix: guard null config" git push -u origin hotfix/2.3.1

The ordering matters: git switch -c before the commit also works, and is what the error message suggests, but doing it after the commit is equally safe as long as you have not left the commit.

2. Commits already lost after switching branches

git reflog records every movement of HEAD for 90 days by default (gc.reflogExpire), with unreachable objects kept for 30 (gc.reflogExpireUnreachable). Find the commit by message and take it into a branch — do not git reset first.

bash
git reflog --date=iso | head -20 git show HEAD@{3} --stat git switch -c recovered HEAD@{3}

If the reflog has expired, git fsck --lost-found --unreachable lists dangling commits; git show <sha> identifies them by their diff.

3. Rebasing a branch that is already pushed

git rebase rewrites shas, so the remote copy is no longer an ancestor and the push is rejected again. That is expected: after rebasing your own feature branch, the correct push is --force-with-lease, and on a shared branch it is a pull request instead.

bash
git fetch origin git rebase origin/main git push --force-with-lease origin feature/login # only if nobody else uses the branch

--force-with-lease refuses if the remote ref is not what your origin/feature/login says — the guard against clobbering a colleague's push in the last few seconds.

4. When pull --rebase produces conflicts on every commit

A long-lived branch with many small commits replays badly. Squash first, or merge instead:

bash
git fetch origin git merge origin/main # one conflict resolution, merge commit git push origin feature/login # fast-forward, no force needed

Merging keeps the pushed history intact, so the push is a fast-forward and no force is required. The cost is a merge commit.

5. CI that force-pushes over the default branch

A workflow doing git push --force origin main after generating files will silently discard other people's commits. Use --force-with-lease at minimum, and better, only push generated output to a dedicated branch or a bot branch that a human merges:

yaml
- run: | git config user.name "ci-bot" git config user.email "ci@example.com" git add -A git commit -m "chore: regenerate" || exit 0 git push origin HEAD:bot/generated --force-with-lease

6. Shallow clones in CI

actions/checkout defaults to fetch-depth: 1, so git describe, tag-based versioning, and rebases against origin/main fail with fatal: refusing to merge unrelated histories or shallow update not allowed. Fetch what the job needs:

bash
git fetch --unshallow --tags origin git fetch origin main:refs/remotes/origin/main

Common Compilation/Runtime Mistakes & Version Gotchas

  • git checkout . to "reset". It discards unstaged changes in the working tree; when you meant to leave a detached HEAD, it is the wrong command in the same family.
  • git reset --hard origin/main as a habit. It deletes local commits with no reflog entry for the branch, and it is the most common way work is lost after a rejected push.
  • Plain --force. It overwrites whatever is on the remote at that moment, including a colleague's commit pushed a second earlier. --force-with-lease (and --force-if-includes on newer Git) checks first.
  • git switch vs git checkout. git switch (2.23+) changes branches only and refuses ambiguous refs, which makes detached-HEAD mistakes rarer; git checkout <file> still means "restore file".
  • pull.rebase left at the default. A merge-on-pull workflow turns every sync into a merge commit and every later rebase into a conflict marathon. Set git config --global pull.rebase true if your team rebases.
  • Tags are not branches. git checkout v1.0 is always detached by design; git checkout -B release/1.0 v1.0 creates the branch and moves it.
  • Submodules report detached HEAD by default. git submodule update checks out a commit, so edits inside a submodule have the same problem — branch before committing, then update the parent's gitlink.

Related tools. Compare the two sides of a divergence line by line before choosing rebase or reset with the text diff, hash the tree at HEAD@{1} and today's HEAD with the hash generator to confirm a recovery restored exactly the earlier tree, and decode the JSON payload of a Git hosting webhook or API response with the JSON formatter when a protected-branch rejection only names it by code.

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.