git commit --amend does not create a new commit. It replaces the last
one. Precisely: it creates a new commit with updated content and moves the
branch to it. The old commit remains in .git/objects/ as a dangling
object.
What you can do
Fix the message
git commit --amend -m "new message"
# Without -m, the editor opens with the current message.
git commit --amend
Add a forgotten file
git add forgot.js
git commit --amend --no-edit
# --no-edit keeps the old message; the file is folded into the commit.
Fix the content
If you committed and immediately spotted a bug, fix the file, stage it,
then --amend. You get a correct commit instead of a separate "fix
previous commit" entry.
What physically happens
- The current index is taken (including new edits, if any).
- A new commit object is created:
- tree: from the current index
- parent: the same as the old commit's parent (not the old commit itself)
- author/committer/message: from the old commit, plus your changes
- The current branch moves to the new SHA.
- The old commit becomes dangling.
The old commit is visible in reflog for about a month. If you made a
mistake in the amend, you can recover it with git reflog.
When not to use it
If the commit was already pushed and someone else pulled it, --amend
breaks history. You have one SHA locally; others have a different one.
A regular push will fail:
! [rejected] feature -> feature (non-fast-forward)
Options:
- Force-push with
--force-with-lease. Safe only for a feature branch that nobody else is watching. - Do not amend. Create a new commit instead. This is the right approach
for
main/masterand any shared branch.
Rule: amend is allowed before the first push. After push, only on personal branches, only with force-with-lease.
Pitfalls
- Author date.
--amendkeeps the author date unchanged but updates the committer date.git log --pretty=fullershows both. - GPG signatures. If the commit was signed, the signature is dropped
after
--amend. Re-sign withgit commit --amend -S. - Ordering.
git logsorts by committer date by default. After an amend the commit floats to the top, even if the author date is old.