Undoing Common Mistakes
Everyone makes mistakes with Git — committing to the wrong branch, writing a bad commit message, or accidentally staging the wrong file. Git provides safe ways to fix nearly all of these.
Knowing which command to use for which mistake (restore, reset, revert, or reflog) helps you fix problems quickly and confidently instead of panicking.
git commit --amend -m "corrected message"Fixing the last commit
Use `git commit --amend -m "new message"` to fix the most recent commit's message, or `git commit --amend --no-edit` after staging a forgotten file to add it to the last commit.
Common fixes at a glance
Wrong staged file: `git restore --staged file`. Wrong commit message: `git commit --amend`. Bad commit already pushed: `git revert`. Accidentally deleted branch: recover with `git reflog`.
git commit -m "fix bugg"
git commit --amend -m "Fix bug in checkout flow"[main 2b7a1ee] Fix bug in checkout flowCorrects a typo-ridden commit message by amending the most recent commit.
git add forgotten-file.js
git commit --amend --no-edit[main 2b7a1ee] Fix bug in checkout flowAdds a forgotten file into the previous commit without changing its message.
Key points
- git commit --amend fixes the most recent commit's message or contents.
- git restore --staged fixes accidentally staged files.
- git revert safely undoes a commit that's already been pushed and shared.
- git reflog can recover branches or commits thought to be lost.
