Everyone breaks something in Git sooner or later. These are the situations I see most often, with the fix for each.

I committed to the wrong branch

Move the commit to a new branch, then remove it from the old one:

git branch feature-fix # new branch pointing at the same commit git reset --hard HEAD~1 # remove the commit from the current branch git checkout feature-fix 

I need to change my last commit message

git commit --amend -m "Better message" 

Only do this if you haven't pushed yet.

I want to undo a commit but keep my changes

git reset --soft HEAD~1 

Your files stay as they were, and the commit disappears from history.

I changed a file and want to throw the changes away

git restore path/to/file 

This cannot be undone, so check with git status first.

I need to switch branches but I'm not ready to commit

git stash git checkout other-branch # later git stash pop 

I pushed something and need to undo it safely

Use revert instead of rewriting history. It creates a new commit that cancels the old one:

git revert <commit-hash> 

One habit that prevents most problems

Run git status and git diff before every commit. It takes five seconds and catches most mistakes.

What Git mistake taught you the most? Share it below.