Tour of Git
Git Basics / Lesson 1.9

git commit --amend — Fixing the Last Commit

Made a typo in your commit message? Forgot to include a file? The --amend flag lets you fix the most recent commit without creating a new one.

Fixing the Commit Message

If you just need to reword the last commit:

git commit --amend -m "Corrected commit message"

This replaces the old message with the new one. The commit hash will change because the content of the commit object is different.

Adding Forgotten Files

If you forgot to stage a file before committing:

git add forgotten-file.txt
git commit --amend --no-edit

The --no-edit flag keeps the existing commit message. The forgotten file is now part of the last commit as if it was always there.

What Actually Happens

Amending doesn't truly "edit" the old commit. Git creates a new commit that replaces the previous one. The old commit becomes unreferenced and will eventually be garbage collected.

Before amend:

A --- B (HEAD)

After amend:

A --- B' (HEAD)    (B is discarded)

When NOT to Amend

  • Never amend commits that have been pushed to a shared repository. Other people may have based their work on the original commit. Amending would rewrite history and cause conflicts.
  • Only amend your local, unpushed commits.

Try it!

The repository is already initialized. Make a commit, then fix it:

  1. Create a file: echo "hello" > greeting.txt
  2. Stage and commit with a typo: git add greeting.txt then git commit -m "Add greting file"
  3. Check the log: git log --oneline (notice the typo)
  4. Fix the message: git commit --amend -m "Add greeting file"
  5. Check the log again: git log --oneline (message is fixed, hash changed)
  6. Now add a forgotten file: echo "goodbye" > farewell.txt
  7. Stage it: git add farewell.txt
  8. Amend without changing the message: git commit --amend --no-edit
  9. Verify both files are in the last commit: git log --oneline (still one commit ahead)

Watch how the commit hash changes each time you amend!

🎯

Goal

Make a commit, then amend it with a better message

Terminal
$

No commits yet. Run `git init` and create your first commit.