Tutorial

10 Git Scenarios Every Developer Faces

You don't need to memorize Git. You need to know what to run when something goes wrong. Here are the 10 situations I hit most often, with the exact commands.

1. Undo Last Commit (Keep Changes)

git reset --soft HEAD~1

Removes the commit but keeps your files staged. Use when you committed too early.

2. Undo Last Commit (Discard Changes)

git reset --hard HEAD~1

?��? Destructive. Removes commit AND changes. Only use when you're sure.

3. Fix the Last Commit Message

git commit --amend -m "New message here"

Only safe if you haven't pushed yet.

4. Stash Changes Temporarily

git stash
# ... switch branches, do other work ...
git stash pop

Saves uncommitted work so you can switch context cleanly.

5. Resolve a Merge Conflict

# After git merge or git pull shows conflicts:
# 1. Open conflicted files, look for <<<<<<< markers
# 2. Edit to keep what you want
# 3. Stage and commit:
git add .
git commit -m "Resolve merge conflict"

6. Recover a Deleted Branch

git reflog
# Find the commit hash before deletion
git checkout -b recovered-branch abc1234

reflog is your safety net. Git rarely truly deletes anything.

7. Undo a File to Last Commit

git checkout -- filename.js
# or (newer syntax):
git restore filename.js

Discards uncommitted changes to one file.

8. Squash Last 3 Commits into One

git rebase -i HEAD~3
# In the editor, change "pick" to "squash" for commits 2 and 3

Clean up messy history before opening a PR.

9. Push to Remote (First Time)

git remote add origin https://github.com/user/repo.git
git branch -M main
git push -u origin main

10. Pull with Rebase (Cleaner History)

git pull --rebase origin main

Puts your commits on top of remote changes instead of creating a merge commit.

Quick Reference Card

I want to...Command
Undo commit, keep filesgit reset --soft HEAD~1
Save work temporarilygit stash
Discard file changesgit restore file
Find lost commitsgit reflog
Update from remotegit pull --rebase
Git doesn't punish mistakes - it records everything. reflog is your undo button for the undo button.
In This Article
  • 1. Undo Commit (Keep)
  • 2. Undo Commit (Discard)
  • 3. Fix Commit Message
  • 4. Stash Changes
  • 5. Merge Conflicts
  • 6. Recover Branch
  • 7. Restore File
  • 8. Squash Commits
  • 9. First Push
  • 10. Pull with Rebase