Q30 of 40 · Git
Your local Git repository is reporting corrupted objects or a detached HEAD you can't escape. How do you diagnose and recover?
Short answer
Short answer: `git fsck --full` finds corrupted or dangling objects. For detached HEAD, `git switch -` returns to the previous branch. For corrupt objects, re-fetch from the remote or restore from a healthy clone. `git reflog` can recover lost commits.
Detail
Diagnosing corruption: git fsck --full walks the entire object database and reports missing, dangling, or corrupt objects. "Dangling commit" or "dangling blob" entries are usually harmless (unreachable objects before GC). An "error: object file is empty" or "error: corrupt loose object" indicates actual disk-level corruption.
Recovery strategies:
- Re-fetch objects:
git fetch --allre-downloads all remote objects. Git's object store is content-addressed, so fetching re-creates any object whose SHA matches the remote's copy. - Re-clone: the nuclear option —
git clone <url> fresh-repo. Copy any uncommitted work manually. Usually faster than debugging deep corruption. - Restore specific objects from packfiles:
git unpack-objectsandgit cat-filecan extract objects from pack files on a healthy clone.
Detached HEAD: occurs after git checkout <sha>, git bisect, or a failed rebase. Run git switch - to return to the previous branch, or git switch main to go directly to a named branch. If you made commits in detached HEAD state, save the SHA (git log --oneline -1), switch back, then cherry-pick those commits.
Reflog as safety net: git reflog records every position HEAD has been at for the past 90 days. Even after a --hard reset or accidental branch delete, git reflog lets you find and restore the commit.
// EXAMPLE
# --- Diagnose repository health ---
git fsck --full
# "dangling commit abc123" — harmless, will be GC'd
# "error: corrupt loose object 'def456'" — real problem
# --- Fix: re-fetch objects from remote ---
git fetch --all
# --- Fix: if still broken, re-clone ---
# (save uncommitted work first)
git stash
cd ..
git clone https://github.com/company/repo.git repo-fresh
cd repo-fresh
git stash apply # re-apply WIP
# --- Escape from detached HEAD ---
# Check where you are
git log --oneline -1
git status # shows "HEAD detached at a1b2c3"
# Save the SHA if you made commits here
LOST_SHA=$(git rev-parse HEAD)
# Return to previous branch
git switch -
# Or go directly to main
git switch main
# Cherry-pick commits you made in detached HEAD
git cherry-pick $LOST_SHA
# --- Find lost commits via reflog ---
git reflog --all | head -20
git switch -c recovered-work HEAD@{3}