0
0
GitDebug / FixBeginner · 4 min read

How to Fix a Corrupted Git Repository Quickly and Safely

To fix a corrupted git repository, first try running git fsck to identify issues, then use git reflog and git reset --hard to recover to a good state. If corruption persists, clone a fresh copy or restore from backup.
🔍

Why This Happens

Git repositories can become corrupted due to interrupted operations, disk errors, or manual file changes. This causes Git to fail reading objects or refs, breaking normal commands.

bash
git status
fatal: bad object HEAD
Output
fatal: bad object HEAD
🔧

The Fix

Run git fsck to find corrupted objects. Use git reflog to find a recent good commit. Then reset your branch to that commit with git reset --hard <commit-hash>. If needed, reclone the repository.

bash
git fsck
# shows corrupted objects

git reflog
# find last good commit hash

git reset --hard abc1234
# reset to good commit
Output
Checking object directories: 100% (256/256), done. error: object file .git/objects/ab/cdef1234 is empty fatal: loose object ab/cdef1234 (stored in .git/objects/ab/cdef1234) is corrupt HEAD@{0}: reset: moving to abc1234
🛡️

Prevention

Always avoid interrupting Git commands. Use reliable storage and backups. Regularly run git gc to clean and optimize the repository. Avoid manual changes inside the .git folder.

⚠️

Related Errors

Other common Git errors include fatal: unable to read tree and error: object file is empty. These often have similar fixes like running git fsck and resetting to a good commit.

Key Takeaways

Run git fsck to detect corruption in your repository.
Use git reflog to find a safe commit to reset to.
Avoid interrupting Git commands to prevent corruption.
Keep backups and clone fresh copies if corruption is severe.
Regularly run git gc to maintain repository health.