Lesson 04 of 05Concept

Amend Your Last Commit

Goal: Correct a recent commit with git commit --amend, and know when it is safe to do so.

You commit, and a second later you see it: a typo in the message, or a file you forgot to stage. You could add a second commit called "oops", or you could fix the last one.

git commit --amend replaces the most recent commit with a new one. It is the tidiest way to fix a mistake you have not shared yet.

Amending replaces, it does not edit

Commits are immutable: their id is a hash of their contents, so changing anything changes the id. --amend therefore does not edit the last commit. It builds a new commit from the same parent, using the current staging area and the message you give it, and moves the branch onto it.

The original commit is still in the repository for a while, reachable through git reflog, but nothing points at it any more.

Fixing a forgotten file

Step 1 of 3

"Add login form" is committed, but login.css was never staged. It is still sitting in the working tree.

Step 1 of 3. "Add login form" is committed, but `login.css` was never staged. It is still sitting in the working tree.

The two jobs it does

Fix the message

  • git commit --amend -m "Add login form"
  • Nothing staged, so only the message changes
  • Useful for typos and missing context

Fix the contents

  • git add the file, then git commit --amend --no-edit
  • --no-edit keeps the existing message
  • Folds the forgotten change into the commit where it belongs

What the reflog shows afterwards

$ git reflog

8d4c21e (HEAD -> main) HEAD@{0}: commit (amend): Add login form
3af09b7 HEAD@{1}: commit: Add login form
1b7e55c HEAD@{2}: commit: Add homepage

Two entries, two different ids, the same message. HEAD@{1} is the commit you replaced, so git reset --hard HEAD@{1} undoes the amend if you change your mind.

Finished reading?

Marking it complete records your progress and XP for this lesson.