Undoing and recovery

Practice repairing an incomplete local commit

Create an incomplete commit in notes-project, inspect the staged changes, amend it, and verify the replacement snapshot.

In this exercise, we will leave a file out of a local commit, then repair the snapshot. Use a throwaway notes-project repository so you can compare the original and replacement commits safely.

For the command reference and the -m option, see how to add a forgotten file to a Git commit.

Create the incomplete snapshot

Start in a new folder, with Git already configured with your name and email:

mkdir notes-project
cd notes-project
git init
printf '%s\n' '# Notes' > README.md
printf '%s\n' 'Build a search page' > ideas.txt
git add README.md
git commit -m "Start the notes project"
git rev-parse HEAD

Save that commit ID. The README is committed, but ideas.txt is still untracked.

Check the snapshot and working tree:

git status
git show --stat --oneline HEAD

Only README.md should appear in the commit. If both files appear, repeat the exercise in another empty folder.

Inspect what will change

Stage the missing file, then read the staged diff:

git add ideas.txt
git diff --staged

The diff should add one line to ideas.txt. If it includes unrelated changes, unstage those before continuing. An amend includes everything currently staged.

Replace the last commit while keeping its message:

git commit --amend --no-edit

Verify the repair

git show --stat --oneline HEAD
git status
git rev-parse HEAD

The new commit should list both files, the working tree should be clean, and the commit ID should differ from the one you saved. Git created a replacement commit from the index.

Now add another idea, stage it, and amend again. Check git log --oneline: there should still be one commit at the tip, rather than a separate correction commit.

Only do this with commits still private to your local branch. If someone has pulled the commit, make a normal follow-up commit. Replacing a shared commit requires coordination because other people still have the old history.

For other mistakes, the Git recovery tool gives you step-by-step commands.

Lesson completed