Git & GitHub · Chapter 40 of 42

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.

Syntax
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`.

Example 1 (bash)
git commit -m "fix bugg"
git commit --amend -m "Fix bug in checkout flow"
Output
[main 2b7a1ee] Fix bug in checkout flow

Corrects a typo-ridden commit message by amending the most recent commit.

Example 2 (bash)
git add forgotten-file.js
git commit --amend --no-edit
Output
[main 2b7a1ee] Fix bug in checkout flow

Adds 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.
💡 Note: Never amend or rewrite commits that have already been pushed and pulled by others — use revert instead in that case.

📝 Quick Quiz

1. Which command fixes the message of the most recent commit?

2. What should you use to undo a commit that's already been pushed and shared?

3. What can help recover a branch you think you deleted permanently?