Q17 of 40 · Git

How do you fix a commit message or add a forgotten file to the most recent commit without creating a new commit?

GitMidgitamendcommithistoryworkflow

Short answer

Short answer: `git commit --amend` rewrites the last commit: `--amend -m 'new msg'` fixes the message; staging forgotten files first then `--amend --no-edit` adds them. Never amend a commit already pushed to a shared branch.

Detail

git commit --amend replaces the last commit with a brand-new commit object. The old commit is discarded and a new SHA is generated, which is why amending pushed commits is dangerous — it rewrites history that others may already have pulled.

For a message-only fix, run git commit --amend -m "corrected message" or just git commit --amend to open the editor. For adding a forgotten file, stage the file first (git add forgotten.java) then run git commit --amend --no-edit — the --no-edit flag reuses the existing message so no editor opens.

When it's safe: amending is safe when the commit hasn't been pushed, or when you own the branch exclusively and can force-push (with --force-with-lease). If the commit is on a shared branch like main or a PR branch that others are working from, create a new fixup commit instead and squash it during the PR merge.

Alternative for older commits: if the commit to fix is not the most recent one, use interactive rebase: git rebase -i HEAD~N, then mark the target commit as reword (message) or edit (content).

// EXAMPLE

# Fix the commit message only (opens editor)
git commit --amend

# Fix the message inline (no editor)
git commit --amend -m "fix: correct null-check in UserService"

# Add a forgotten file without changing the message
git add src/test/resources/schema/user.json
git commit --amend --no-edit

# Verify the updated commit
git log --oneline -1

# If already pushed to YOUR branch only — force-push safely
git push --force-with-lease origin feature/my-branch

// WHAT INTERVIEWERS LOOK FOR

Knowing --amend changes the SHA (new commit object), making it unsafe after pushing to shared branches. Knowing --no-edit for adding files silently. Awareness of interactive rebase for older commits.

// COMMON PITFALL

Running `git commit --amend` on a commit that is already on `main` or a shared PR branch, then force-pushing — this rewrites history that teammates have pulled and causes diverged branches.