Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
menu
  1. Home
  2. /Web Development
  3. /Github
  4. /Common Git Problems Solutions
Your Progress0%
0 of 20 completed

Git & Github Topics

Getting Started

  • What is Git?
  • What is GitHub?
  • Installing & Configuring Git
  • Your First Git Repository

Core Git Concepts

  • Understanding Commits & History
  • Working with Branches
  • Merging Branches
  • The Staging Area
  • Undoing Changes

Working with GitHub

  • Connecting to GitHub
  • Pushing & Pulling Code
  • Cloning Repositories
  • GitHub README & Documentation

Collaboration Workflows

  • Forking & Pull Requests
  • Code Review Basics
  • Handling Merge Conflicts
  • Issues & Project Management

Best Practices & Workflows

  • Git Workflow Best Practices
  • Working with .gitignore
  • Common Git Problems & Solutions

Common Git Problems & Solutions

Troubleshoot and fix common Git issues with confidence

Even experienced developers encounter Git problems. The difference is knowing how to fix them quickly and confidently. In this final lesson, you'll learn to troubleshoot common Git issues, recover from mistakes, handle detached HEAD state, undo unwanted changes, find lost commits, and navigate tricky situations. Think of this as your Git emergency handbook—when things go wrong, you'll know exactly what to do. By the end, you'll approach Git problems with confidence rather than panic!

Troubleshooting Mindset

Remember: Git is designed to prevent data loss. Almost everything is recoverable!

The Troubleshooting Process

  1. Don't panic: Take a breath, you can fix this
  2. Understand the problem: What were you trying to do?
  3. Check status: Run git status
  4. Read error messages: They often tell you exactly what to do
  5. Look at history: Use git log and git reflog
  6. Try the safe option first: Start with non-destructive commands
  7. Create a backup branch: Before risky operations

🛟 Always Start with git status

git status shows you the current state and often suggests what to do next. Make it your first command when troubleshooting!

Problem: Detached HEAD State

What It Is

Detached HEAD happens when HEAD points to a commit instead of a branch.

You'll see:

TEXT
You are in 'detached HEAD' state. You can look around, make
experimental changes and commit them, and you can discard any
commits you make in this state without impacting any branches.

How It Happens

BASH
# Checking out a specific commit
git checkout a1b2c3d

# Checking out a tag
git checkout v1.0.0

# Checking out a remote branch without creating local branch
git checkout origin/main

Solution 1: Just Looking Around

If you just want to look, simply return to a branch:

BASH
# Go back to your branch
git checkout main

# Or
git switch main

Solution 2: Keep Changes Made in Detached HEAD

BASH
# You made commits in detached HEAD and want to keep them

# 1. Create a new branch from current position
git branch new-feature-branch

# 2. Switch to it
git checkout new-feature-branch

# Now your commits are on a proper branch!

Solution 3: Merge Changes to Existing Branch

BASH
# You made commits in detached HEAD

# 1. Note the commit hash
git log --oneline -1
# Output: a1b2c3d Your commit message

# 2. Switch to your branch
git checkout main

# 3. Merge the detached HEAD commits
git merge a1b2c3d

💡 Detached HEAD Prevention

To checkout old commits for inspection without detached HEAD:

BASH
# Create a temporary branch instead
git checkout -b temp-branch a1b2c3d

# When done
git checkout main
git branch -d temp-branch

Problem: Need to Undo Commits

Scenario 1: Undo Last Commit (Keep Changes)

BASH
# Move back one commit, keep changes staged
git reset --soft HEAD~1

# Now you can:
# - Edit files
# - Stage more changes
# - Commit again with better message

Scenario 2: Undo Last Commit (Keep Unstaged)

BASH
# Move back one commit, keep changes unstaged
git reset HEAD~1
# or
git reset --mixed HEAD~1

# Changes are in working directory but not staged

Scenario 3: Undo Last Commit (Discard Everything)

Warning: This permanently deletes changes!

BASH
# Move back and discard all changes
git reset --hard HEAD~1

# Everything from that commit is gone!

Scenario 4: Undo Multiple Commits

BASH
# View history to decide how far back
git log --oneline

# Reset to specific commit
git reset --soft abc123

# Or go back N commits
git reset --soft HEAD~3

Scenario 5: Undo Published Commit (Use Revert)

If the commit was pushed, don't use reset—use revert:

BASH
# Create a new commit that undoes the change
git revert HEAD

# Or revert specific commit
git revert abc123

# Safe for shared history!

Problem: Committed to Wrong Branch

Scenario: Committed to Main Instead of Feature Branch

BASH
# Current situation: You're on main with commits meant for feature branch

# Step 1: Create feature branch from current position
git branch feature/my-work

# Step 2: Reset main to before your commits
git reset --hard origin/main

# Step 3: Switch to feature branch
git checkout feature/my-work

# Now your commits are on the right branch!

Alternative: Cherry-Pick Approach

BASH
# If you only want specific commits

# 1. Note the commit hashes you want
git log --oneline

# 2. Create and switch to feature branch
git checkout -b feature/my-work origin/main

# 3. Cherry-pick the commits
git cherry-pick abc123
git cherry-pick def456

# 4. Reset main
git checkout main
git reset --hard origin/main

Problem: Deleted Branch or Lost Commits

Recover Deleted Branch

BASH
# Oops, accidentally deleted a branch
# git branch -D feature-branch

# Step 1: Find the last commit using reflog
git reflog

# Look for something like:
# a1b2c3d HEAD@{2}: commit: Last commit on feature-branch
# f4e5d6c HEAD@{3}: checkout: moving from feature-branch to main

# Step 2: Recreate the branch pointing to that commit
git branch feature-branch a1b2c3d

# Branch recovered!

Find Lost Commits

BASH
# View all HEAD movements (last 30 days)
git reflog

# Find commits that seem lost
# a1b2c3d HEAD@{5}: commit: Important work

# Create branch or reset to that commit
git branch recovered-work a1b2c3d

# Or reset current branch
git reset --hard a1b2c3d

Find Truly Lost Commits (Unreachable)

BASH
# Find commits not referenced by any branch or reflog
git fsck --lost-found

# Shows dangling commits:
# dangling commit a1b2c3d4e5f6

# View the commit
git show a1b2c3d4e5f6

# If it's what you need, create a branch
git branch recovered a1b2c3d4e5f6

🔒 Git Keeps Everything

Git keeps "lost" commits for ~30 days. During this window, you can usually recover them using reflog or fsck!

Problem: Merge Gone Wrong

Abort a Merge in Progress

BASH
# Started a merge but want to cancel it
git merge --abort

# Repository returns to state before merge
# Safe to use at any point during conflict resolution

Undo a Completed Merge

BASH
# Merged but want to undo it

# Option 1: Reset (if not pushed)
git reset --hard HEAD~1

# Option 2: Revert (if pushed)
git revert -m 1 HEAD
# -m 1 means "keep the first parent" (usually your branch)

Resolve: Conflicts Too Complex

BASH
# Conflicts are overwhelming

# Option 1: Abort and rethink strategy
git merge --abort

# Option 2: Accept one side completely
git checkout --ours conflicted-file.txt    # Keep your version
git checkout --theirs conflicted-file.txt  # Keep their version
git add conflicted-file.txt
git commit

# Option 3: Ask for help!
# Pair with teammate to resolve together

Problem: File Management Issues

Accidentally Staged Wrong Files

BASH
# Staged everything including files you didn't want
git add .

# Unstage specific file
git restore --staged unwanted-file.txt

# Or unstage everything
git restore --staged .

Accidentally Committed Sensitive File

Critical: If you committed passwords or API keys:

BASH
# 1. IMMEDIATELY rotate/change the secret (it's compromised!)

# 2. Remove from latest commit (if not pushed yet)
git reset HEAD~1
git restore --staged .env
echo ".env" >> .gitignore
git add .gitignore
git commit -m "Add .gitignore"

# 3. If already pushed, remove from all history
# Use BFG Repo Cleaner or git filter-repo
git filter-repo --path .env --invert-paths
git push --force

# 4. Everyone must re-clone the repository

Deleted File by Mistake

BASH
# Accidentally deleted a file

# If not committed yet
git restore deleted-file.txt

# If committed but you know which commit had it
git checkout abc123 -- deleted-file.txt

# If you don't know which commit
git log -- deleted-file.txt  # Find last commit with file
git checkout <commit-hash> -- deleted-file.txt

Modified File, Want to Discard Changes

BASH
# Discard changes to specific file
git restore filename.txt

# Discard all changes
git restore .

# WARNING: This permanently deletes uncommitted changes!

Problem: Push/Pull Issues

Push Rejected: Remote Has Changes

Error:

TEXT
! [rejected]        main -> main (fetch first)
error: failed to push some refs
BASH
# Solution: Pull first, then push
git pull origin main

# If conflicts, resolve them
# Then push
git push origin main

Diverged Branches

Message: "Your branch and 'origin/main' have diverged"

BASH
# Option 1: Merge (creates merge commit)
git pull origin main

# Option 2: Rebase (cleaner history)
git pull --rebase origin main

# Then push
git push origin main

Accidentally Pushed to Wrong Remote

BASH
# Pushed to wrong remote
git push wrong-remote main

# If you can, delete from wrong remote
git push wrong-remote :main

# Push to correct remote
git push correct-remote main

Problem: Remote Repository Issues

Can't Connect to Remote

Error: "Permission denied" or "Repository not found"

BASH
# Check your remote URLs
git remote -v

# SSH issues?
# Test SSH connection
ssh -T git@github.com

# If SSH not working, switch to HTTPS
git remote set-url origin https://github.com/username/repo.git

# HTTPS issues?
# Check credentials, make sure using Personal Access Token

Remote Branch Deleted

BASH
# Your local branch tracks a deleted remote branch

# See remote branches
git branch -r

# Prune deleted remote branches
git fetch --prune
# or
git remote prune origin

# Switch to different branch
git checkout main

# Delete local branch if no longer needed
git branch -d old-branch

Problem: Repository State Issues

Repository Seems Corrupted

BASH
# Check repository integrity
git fsck --full

# If issues found, try:
git gc --prune=now

# Still broken? Clone fresh and copy uncommitted work
cd ..
git clone <repository-url> repo-fresh
cd repo-old
# Copy uncommitted files to repo-fresh

Huge Repository Size

BASH
# Check what's taking space
git count-objects -vH

# Clean up
git gc --aggressive --prune=now

# Remove large files from history (if appropriate)
# Use BFG Repo Cleaner or git filter-repo

.git Folder Deleted

If .git folder is deleted, your Git history is gone!

BASH
# No recovery possible locally

# Solution: Clone from remote
git clone <repository-url>

# Copy your uncommitted work from old directory
# Your commits are safe on GitHub/remote

Emergency Procedures

When You're Really Stuck

1. Create a Backup

BASH
# Before trying anything drastic
cp -r my-project my-project-backup

# Or create a Git bundle
git bundle create ../backup.bundle --all

2. Reflog Is Your Friend

BASH
# View all recent HEAD movements
git reflog

# This shows EVERYTHING you've done recently
# You can almost always recover using reflog

3. When to Start Fresh

Sometimes it's easier to start fresh:

BASH
# Save uncommitted work
git stash

# Or copy files manually
cp -r src ../src-backup

# Clone fresh copy
cd ..
git clone <repository-url> project-fresh

# Copy uncommitted work back
# Investigate what went wrong before committing again

4. Ask for Help

  • Teammates: Explain the situation, they might know the fix
  • Git documentation: git help <command>
  • Stack Overflow: Someone probably had the same issue
  • Git IRC/Discord: Real-time help from experts

Preventing Common Problems

Good Habits to Develop

  • Commit often: Small commits are easier to manage
  • Pull before pushing: Stay synchronized
  • Use branches: Keep main stable
  • Review before committing: git diff and git status
  • Use .gitignore: Don't commit sensitive files
  • Backup regularly: Push to remote frequently
  • Test before committing: Ensure code works

Aliases for Common Fixes

BASH
# Add helpful aliases
git config --global alias.undo 'reset --soft HEAD~1'
git config --global alias.unstage 'restore --staged'
git config --global alias.discard 'restore'
git config --global alias.amend 'commit --amend --no-edit'
git config --global alias.oops 'reset HEAD~1'

# Now you can use:
git undo       # Undo last commit, keep changes
git unstage .  # Unstage all files
git discard .  # Discard all changes
git amend      # Add to last commit
git oops       # Undo last commit

Practice Recovery Commands

Try these commands for troubleshooting and recovery:

Practice Git Recovery

Explore reflog and recovery commands

$

Try these examples:

Quick Reference: Common Problems

TEXT
Problem                          | Solution
---------------------------------|----------------------------------
Detached HEAD                    | git checkout main
Undo last commit (keep changes)  | git reset --soft HEAD~1
Undo last commit (discard)       | git reset --hard HEAD~1
Wrong branch                     | git branch temp; git reset --hard origin/main; git checkout temp
Deleted branch                   | git reflog; git branch branch-name <hash>
Lost commits                     | git reflog; git reset --hard <hash>
Merge conflicts too complex      | git merge --abort
Abort merge                      | git merge --abort
Unstage file                     | git restore --staged <file>
Discard changes                  | git restore <file>
Remove from last commit          | git reset HEAD~1; git restore --staged <file>
Push rejected                    | git pull; resolve conflicts; git push
Diverged branches                | git pull --rebase
Can't connect to remote          | Check git remote -v; verify credentials
Corrupted repo                   | git fsck; git gc; or clone fresh

Key Takeaways

  • Git is designed to prevent data loss—most things are recoverable
  • Always start troubleshooting with git status
  • Detached HEAD is safe—just create a branch or return to main
  • Use git reset --soft to undo commits while keeping changes
  • git reflog is your time machine—it shows all HEAD movements
  • Create backup branches before risky operations
  • Deleted branches can be recovered using reflog (within ~30 days)
  • Use git merge --abort to cancel problematic merges
  • Never force push to shared branches without team coordination
  • When stuck, create a backup, check reflog, or ask for help

Conclusion: You've Mastered Git!

Congratulations! You've completed all 20 lessons of this comprehensive Git & GitHub tutorial series! 🎉

You started with basic version control concepts and now you can:

  • ✅ Use Git for version control with confidence
  • ✅ Create branches and merge changes effectively
  • ✅ Collaborate on GitHub through forks and pull requests
  • ✅ Review code professionally and give constructive feedback
  • ✅ Resolve merge conflicts without fear
  • ✅ Manage projects with GitHub Issues and Projects
  • ✅ Follow professional Git workflows and best practices
  • ✅ Protect sensitive data with .gitignore
  • ✅ Troubleshoot and recover from Git problems

What's Next?

Your Git journey doesn't end here:

  • Practice daily: Use Git for all your projects
  • Contribute to open source: Apply your skills in real projects
  • Learn advanced topics: Git hooks, submodules, git bisect
  • Explore GitHub Actions: Automate workflows with CI/CD
  • Master Git internals: Understand how Git works under the hood
  • Help others: Share your knowledge, review PRs

🎓 Keep Learning!

Git is a tool you'll use throughout your entire development career. The more you practice, the more natural it becomes. Don't be afraid to make mistakes—that's how you learn!

Remember: Every expert developer was once a beginner who didn't give up. You've got this! 🚀

Thank you for completing this tutorial series!

We hope these lessons have given you the confidence to use Git and GitHub professionally. Continue practicing, stay curious, and happy coding!

Test Your Understanding of Git Troubleshooting

Question 1 of 4

What is 'detached HEAD' state?

Current Score0 / 0

Just completed this comprehensive Git & GitHub tutorial! 🎉

Previous
Working with .gitignore

Stay Updated with New Tutorials

You've completed the Git & GitHub series! Subscribe to get notified about new tutorials, advanced Git topics, and exclusive developer resources.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

Git & Github Tutorials

0 of 20 completed

Your Progress0%

Topics

Getting Started

  • What is Git?
  • What is GitHub?
  • Installing & Configuring Git
  • Your First Git Repository

Core Git Concepts

  • Understanding Commits & History
  • Working with Branches
  • Merging Branches
  • The Staging Area
  • Undoing Changes

Working with GitHub

  • Connecting to GitHub
  • Pushing & Pulling Code
  • Cloning Repositories
  • GitHub README & Documentation

Collaboration Workflows

  • Forking & Pull Requests
  • Code Review Basics
  • Handling Merge Conflicts
  • Issues & Project Management

Best Practices & Workflows

  • Git Workflow Best Practices
  • Working with .gitignore
  • Common Git Problems & Solutions
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo