Undoing and recovery

Amend the last local commit

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

git commit --amend replaces the latest commit on the current branch. I use it for typos in commit messages and for files I forgot to stage. It is a local fix, not a team fix.

Suppose you are in notes-project on main. You committed a README tweak but the message says “Add serach” instead of “Add search”. Inspect before you fix anything:

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

You should see one commit on top and an empty staged diff. Open the editor and fix the message:

git commit --amend

Save and close the editor. Git replaces the commit. The file list stays the same. Only the message (and the commit ID) change.

To include a file 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

Verify with:

git log --oneline -2
git show --stat HEAD

You should still see one commit at the tip, not two stacked fixes.

Another case: you committed README and ideas.txt together but only README was staged. git show --stat HEAD lists README alone. Stage the missing file, run git commit --amend --no-edit, and git show --stat HEAD should list both files in one snapshot.

Amending creates a new commit with a new ID. If you already pushed the old commit, a normal git push gets rejected:

! [rejected]        main -> main (non-fast-forward)

That is Git protecting your teammates. Do not force-push to fix a typo on a shared branch. Make a small follow-up commit instead, or amend only before the first push.

My rule: amend locally, revert on shared branches.

Try this in notes-project: amend a disposable commit, note the old hash from git log -1, amend again, and confirm the hash changed while git log --oneline -2 still shows a single tip commit.

Lesson completed