Skip to main content

Troubleshooting & Recovery

Comprehensive guide to diagnosing and fixing common Git problems, with recovery strategies for various failure scenarios.

Common Error Messages

Authentication Issues

# Error: Permission denied (publickey)
# Solution 1: Check SSH key setup
ssh -T git@github.com
ssh-add -l # List loaded keys
ssh-add ~/.ssh/id_rsa # Add key if needed

# Solution 2: Switch to HTTPS
git remote set-url origin https://github.com/user/repo.git

# Error: HTTP 403 Forbidden
# Solution: Check credentials and permissions
git config --global credential.helper store
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

Push/Pull Failures

# Error: ! [rejected] main -> main (non-fast-forward)
# Solution 1: Pull first, then push
git pull origin main
git push origin main

# Solution 2: Rebase instead of merge
git pull --rebase origin main
git push origin main

# Solution 3: Force push (dangerous)
git push --force-with-lease origin main

# Error: ! [rejected] main -> main (fetch first)
git fetch origin
git merge origin/main # or git rebase origin/main
git push origin main

Merge Conflicts

# Error: Automatic merge failed; fix conflicts and then commit
git status # See conflicted files
git diff # See conflict markers

# Resolve conflicts:
# Edit files to remove <<<<<<< ======= >>>>>>> markers
git add resolved-file.txt
git commit # Complete the merge

# Or abort the merge
git merge --abort

# Use merge tools
git mergetool
git config --global merge.tool vimdiff

Branch Issues

# Error: pathspec 'branch-name' did not match any file(s)
git fetch origin # Update remote references
git branch -a # List all branches
git switch -c local-branch origin/remote-branch

# Error: Your branch is behind 'origin/main' by X commits
git pull origin main # Get updates
git rebase origin/main # Alternative to merge

# Error: fatal: A branch named 'X' already exists
git branch -d existing-branch # Delete if safe
git branch -D existing-branch # Force delete
git switch existing-branch # Or just switch to it

File and Directory Issues

Missing Files

# File accidentally deleted
git status # Check if deletion is staged
git restore filename.txt # Restore from last commit
git checkout HEAD~1 -- filename.txt # Restore from earlier commit

# File not found in repository
git ls-files | grep filename # Check if file is tracked
git log --follow -- filename.txt # See file history
git show HEAD:filename.txt # Show file content from last commit

.gitignore Problems

# File still tracked despite being in .gitignore
git rm --cached filename.txt # Remove from tracking
git commit -m "Remove tracked file now in gitignore"

# Check what's being ignored
git check-ignore -v filename.txt
git clean -xn # See what would be removed by clean

# Global gitignore not working
git config --global core.excludesfile ~/.gitignore_global

Permission Issues

# Permission denied errors
sudo chown -R $(whoami) .git/ # Fix ownership
chmod -R 755 .git/ # Fix permissions

# File permission changes being tracked
git config core.filemode false # Ignore file mode changes
git update-index --chmod=+x script.sh # Update specific file permissions

Repository Corruption

Corrupt Objects

# Check repository integrity
git fsck
git fsck --full

# Fix corrupt objects
git gc # Garbage collection
git repack -ad # Repack objects

# Severe corruption - recover from remote
git fetch origin
git reset --hard origin/main

Index Lock Issues

# Error: Unable to create '.git/index.lock': File exists
rm .git/index.lock

# If still locked
ps aux | grep git # Find git processes
kill <process-id> # Kill stuck git process
rm .git/index.lock

Reflog Issues

# Recover using reflog
git reflog # Show reference log
git reset --hard HEAD@{1} # Reset to previous state

# Reflog expired or missing
git fsck --lost-found # Find dangling commits
git show <commit-hash> # Check if it's what you need
git branch recovery <commit-hash> # Create branch from lost commit

Workspace Issues

Detached HEAD

# Error: You are in 'detached HEAD' state
git status # Confirm detached state
git switch main # Return to main branch

# If you made commits in detached HEAD
git branch new-branch # Create branch for commits
git switch main
git merge new-branch # Merge if needed

# Save work from detached HEAD
git stash
git switch main
git stash pop

Untracked Files

# Too many untracked files
git clean -n # Dry run - see what would be removed
git clean -f # Remove untracked files
git clean -fd # Remove files and directories
git clean -fx # Remove ignored files too

# Accidentally cleaned files
# Check if files are in .git/lost-found/
ls .git/lost-found/other/

Working Directory vs Index Confusion

# Staged changes disappeared
git diff --staged # Check what's actually staged
git status # Overall status
git reset --mixed # Reset index to match HEAD if needed

# Working directory changes lost
git status # Check current state
git stash list # Check if changes are stashed
git reflog # Check for reset operations

Network and Remote Issues

Clone Failures

# Clone hangs or fails
git clone --depth=1 repo-url # Shallow clone
git clone --single-branch repo-url # Clone only default branch

# Large repository clone issues
git config --global http.postBuffer 1048576000 # Increase buffer
git config --global pack.windowMemory 256m
git config --global pack.packSizeLimit 2g

Fetch/Pull Problems

# Fetch fails with SSL errors
git config --global http.sslVerify false # Temporary fix
git config --global http.sslCAInfo /path/to/ca-certificates.crt

# Slow fetch/pull
git config --global pack.windowMemory 128m
git fetch --depth=1 # Limit history depth

Remote URL Issues

# Wrong remote URL
git remote -v # Check current remotes
git remote set-url origin correct-url
git remote remove old-remote
git remote add origin new-url

Advanced Recovery Scenarios

Lost Commits

# Find lost commits
git reflog --all # Check all references
git fsck --lost-found # Find dangling objects
git log --walk-reflogs # Detailed reflog walk

# Recover specific lost commit
git show <commit-hash> # Verify it's correct
git cherry-pick <commit-hash> # Apply to current branch
git merge <commit-hash> # Or merge if it's a branch tip

Corrupted Branch

# Reset branch to match remote
git fetch origin
git reset --hard origin/main

# Recreate branch from remote
git branch -D corrupted-branch
git fetch origin
git switch -c corrupted-branch origin/corrupted-branch

Split Repository Recovery

# Merge repositories with preserved history
git remote add other-repo path/to/other/repo
git fetch other-repo
git merge --allow-unrelated-histories other-repo/main

# Extract subdirectory as separate repo
git filter-branch --subdirectory-filter subdir/ -- --all

Prevention and Maintenance

Regular Health Checks

# Weekly repository maintenance
git fsck # Check integrity
git gc # Cleanup and optimize
git remote prune origin # Clean remote references

# Check repository size
git count-objects -vH
du -sh .git/

# Verify backups
git bundle create backup.bundle --all
git bundle verify backup.bundle

Backup Strategies

# Create backup before risky operations
git tag backup-$(date +%Y%m%d-%H%M%S)
git branch backup-branch

# Full repository backup
git clone --mirror repo backup-repo
git bundle create full-backup.bundle --all

# Incremental backup
git bundle create incremental.bundle last-backup..HEAD

Configuration for Safety

# Enable helpful warnings
git config --global advice.detachedHead true
git config --global advice.statusHints true

# Set up automatic cleanup
git config --global gc.auto 6700

# Configure merge tools
git config --global merge.tool vimdiff
git config --global mergetool.prompt false

Emergency Procedures

"Nuclear Option" Recovery

# When everything is broken - start fresh but save work
cp -r current-repo broken-repo-backup
git clone original-repo-url fresh-copy
cd fresh-copy

# Selectively copy over important changes
cp ../broken-repo-backup/important-file.txt .
git add .
git commit -m "Recover important changes"

Team Recovery Scenarios

# Someone force-pushed and broke shared branch
git reflog show origin/main # Find previous state
git reset --hard origin/main@{1} # Reset to before force push
git push --force-with-lease origin main # Restore for team

# Multiple people have divergent histories
# Create merge commit that combines everyone's work
git fetch --all
git merge teammate1/main teammate2/main # Octopus merge

Debugging Commands

Diagnostic Commands

# Comprehensive status check
git status --porcelain # Machine-readable status
git status --ignored # Include ignored files

# Detailed diff information
git diff --name-status # Files and their change types
git diff --stat # Statistics summary
git diff --check # Check for whitespace errors

# Branch relationship debugging
git show-branch
git log --graph --oneline --all
git merge-base branch1 branch2 # Find common ancestor

Environment Debugging

# Check Git configuration
git config --list --show-origin
git config --get-all user.name

# Environment variables
env | grep GIT
echo $GIT_DIR
echo $GIT_WORK_TREE

# Git version and features
git --version
git --help -a # All available commands

Performance Debugging

# Identify performance issues
time git status
time git log --oneline -100

# Check object database
git count-objects -v
git verify-pack -v .git/objects/pack/*.idx | sort -k 3 -n | tail -10

# Profile Git operations
GIT_TRACE=1 git status
GIT_TRACE_PERFORMANCE=1 git log --oneline -100

Best Practices for Avoiding Issues

Safe Working Habits

# Always check status before major operations
git status
git log --oneline -5

# Use safe commands
git pull --rebase # Instead of git pull
git push --force-with-lease # Instead of git push --force

# Regular maintenance
git fetch --prune # Clean up remote references
git gc # Regular cleanup
git fsck # Occasional integrity check

Collaboration Safety

# Before pushing to shared branches
git fetch origin
git rebase origin/main # Ensure clean history
git push origin feature-branch

# Never rewrite public history
# Use git revert instead of git reset for shared commits
git revert <commit-hash> # Safe for shared branches

Use this troubleshooting guide alongside Undoing Changes and Advanced Git for comprehensive problem-solving.