Git Common Issues and Fixes Guide

A practical command reference for recovering from common Git mistakes safely.

Back to Guides ยท Home

Goal: help you recover quickly without losing work.

Safety tip: before risky fixes, create a temporary branch: git switch -c rescue/backup-$(date +%Y%m%d-%H%M)

1. "Not a git repository"

# Check current folder
pwd
ls -la

# Enter the correct repository directory
cd /path/to/your/repo

# If needed, initialize a new repo
git init

2. Detached HEAD

# Check status
git status

# Create a branch from current detached commit
git switch -c fix/detached-head-work

# Or return to main branch
git switch main

3. Push Rejected (non-fast-forward)

# Fetch latest remote commits
git fetch origin

# Rebase your branch onto remote
git rebase origin/main

# Resolve conflicts if prompted, then continue
git rebase --continue

# Push after rebase
git push origin main

4. Merge Conflicts

# Start merge/rebase and inspect conflict files
git status

# Edit conflict markers in files, then mark resolved
git add <resolved-file>

# Continue merge/rebase
git merge --continue
# or
git rebase --continue

5. Committed to Wrong Branch

# Example: commit is on main, but should be on feature branch

# 1) Remember latest commit hash
git log --oneline -n 3

# 2) Create target branch from current commit
git switch -c feature/correct-branch

# 3) Return to main and remove wrong commit safely
git switch main
git reset --hard HEAD~1

If the wrong commit was already pushed, use git revert instead of history rewrite on shared branches.

6. Accidentally Lost Commits

# Use reflog to find lost commit refs
git reflog

# Recover by creating a branch at that commit
git switch -c recover/lost-work <commit-hash>

7. Undo Last Commit Safely

# Keep changes staged
git reset --soft HEAD~1

# Keep changes unstaged
git reset --mixed HEAD~1

# Create inverse commit (safe for shared branches)
git revert HEAD

8. Common Error Reference

Error Likely Cause Action
fatal: refusing to merge unrelated histories Two repos with unrelated roots Use --allow-unrelated-histories only if intentional
src refspec ... does not match any No commit yet or wrong branch name Create first commit and verify branch name
Permission denied (publickey) SSH key missing or not registered Check local SSH key and Git host key registration

9. Quick Health Checks

git status
git branch -vv
git remote -v
git log --oneline --graph --decorate -n 20