Undoing and recovery
Git, what if you forgot to add a file to a commit?
Forgot to add a file to your last Git commit? Learn how to use git commit --amend to stage the missing file and optionally fix the commit message.
8 minute lesson
This happens often. You create a commit, then notice that one file stayed in the working tree.
Start by checking exactly what the last commit contains and what remains outside it:
git status
git show --stat --oneline HEAD
git diff -- file-forgotten.txt
If the missing file belongs to that same change, stage it:
git add file-forgotten.txt
git diff --staged
Then replace the last commit while keeping its message:
git commit --amend --no-edit
Amending does not open and modify the old commit. Git creates a new commit from the current index and gives it a new object ID. The current branch moves to the replacement.
Verify the result:
git show --stat --oneline HEAD
git status
Only amend work that is still private to your local branch. If other people may already have the old commit, create a new commit instead. That avoids rewriting shared history.
Exercise: create a commit that intentionally misses one file, record its ID, amend it, then compare the new ID and file list.
For this and other Git mistakes, I made a free Git recovery tool that gives you step-by-step commands to get out of trouble.
Lesson completed