Undoing and recovery

Amend the last local commit

Replace the latest commit when its message or selected files need a small correction.

8 minute lesson

~~~

git commit --amend replaces the latest commit on the current branch.

Before using it, inspect both the latest commit and the index:

git show --stat --oneline HEAD
git diff --staged

To change only the commit message, run:

git commit --amend

To include a correction, stage it first, then amend. The new commit uses the complete current index, not only the last file you staged.

git add README.md
git diff --staged
git commit --amend --no-edit

Amending creates a new commit with a new ID. The parent normally stays the same, but the message, snapshot, author metadata, or committer metadata can differ.

Use amend on local work. Avoid replacing a commit that other people may already have. Their history still contains the old ID, so a later push can require history rewriting and create unnecessary recovery work.

If the commit is already shared, make a normal follow-up commit instead. It is less elegant, but it preserves the common history.

Exercise: amend a disposable commit, then run git log --oneline -2. Explain why the replacement appears as one commit rather than an extra child.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →