Rewriting Git History | git commit --amend
The git commit –amend command
git commit --amend is useful when you need to modify the previous commit. Instead of committing a completely new snapshot, this command combines staged changes with the previous commit. It is also useful when you only want to edit the previous commit message without changing the snapshot.
Git Tutorial: git commit --amend
However, amending the previous commit does not overwrite it in place. It replaces it with an entirely different commit. In Git, it appears as a new commit, like the asterisk in the tutorial diagram. Keep this in mind when working with public repositories.
Usage
git commit --amend
Combines the staged contents with the previous commit and replaces the previous commit with the resulting snapshot. If nothing is staged, this command lets you edit the previous commit message without rewriting the snapshot contents.
Additional notes
Incomplete commits are common in real development. You may forget to stage a file or write a commit message in the wrong format. The --amend flag is useful for fixing these small mistakes.
Do not amend published commits
The git reset page explains why you should not undo commits that are shared with other developers. The same rule applies to amending: do not amend commits that have already been pushed to a public repository.
An amended commit is actually a completely new commit, and the old commit disappears from the visible project history. This causes problems similar to resetting a published commit. If other developers have already based work on the original commit, amending it makes that base appear to be lost. This can confuse developers and make recovery troublesome.
Example
The following example shows a common scenario in Git-based development. You intended to commit changes to two files as one snapshot, but forgot to add one of the files before committing. To fix it, stage the missing file and commit again with --amend:
# Edit hello.py and main.py
git add hello.py
git commit
# Realize you forgot to add the changes from main.py
git add main.py
git commit --amend --no-edit
An editor is normally opened to show the previous commit message. If you use the --no-edit flag, the commit is amended without changing the message. If needed, edit the message, then save and close the file as usual. The resulting commit replaces the incomplete commit and looks as if the changes to hello.py and main.py were committed together in a single snapshot.