Git Common Mistakes
In this page:
Committing to the Wrong Branch
Committing straight to main when you meant to be on a feature branch is fixable without losing the work: create a new branch at your current commit, then reset main back to where it was before (git reset --hard origin/main) so the commit only lives on the new branch.
Example: Committing to the Wrong Branch
git branch feature-x
git reset --hard HEAD~1
git checkout feature-x
Forgetting to Add a File
Realizing you forgot to git add a file after already committing doesn't require a whole new commit — stage the missing file and run git commit --amend --no-edit to fold it into the commit you just made, as long as you haven't pushed yet.
Example: Forgetting to Add a File
git add forgotten-file.txt
git commit --amend --no-edit
Accidental Hard Reset
A git reset --hard that goes further back than intended feels catastrophic, but the commits usually aren't actually deleted — git reflog still records where your branch pointed a moment ago, so you can find the old commit hash and reset back onto it.
Example: Accidental Hard Reset
git reflog
git reset --hard a1b2c3d
Fixing Messy States
When a merge or rebase leaves your branch in a state you don't understand and don't trust, the fastest way out is often not to keep fighting it — git reset --hard origin/<branch> throws away local confusion and realigns you with the last known-good state on the remote (at the cost of any uncommitted local work).
Example: Fixing Messy States
git reset --hard origin/main
Untracking an Already Tracked File
Adding a file to .gitignore does nothing for a file Git is already tracking — ignore rules only apply to *untracked* files. You have to git rm --cached <file> first to stop tracking it, and only then does .gitignore actually keep it out of future commits.
Example: Untracking an Already Tracked File
echo "config.local.json" >> .gitignore
git rm --cached config.local.json
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: