Git commit --amend



The git commit --amend command is a useful way to change the last commit. Instead of creating a completely new commit, you can use the git commit --amend command to combine the staged changes with the previous commit. Also, it can be used to edit the previous commit message without changing its snapshot.

You should be aware that amending does not just modify the last commit. It takes the last commit and replaces it completely with a new entity with its own ref. Git will see the replaced commit like a new commit, which can be visualized with an asterisk(*) in the illustration below.

git commit ammend

Changing the most recent commit message

Suppose you made some mistake in your commit log message. Executing git commit --amend when there is nothing staged lets you modify the last commit message without changing its snapshot.

The git commit --amend can also be used to change the previous commit by modifying its snapshot (e.g. adding a new file you forget to include in the last commit).

The command below will prompt the default editor to change the previous commit:

$ git commit --amend

You can also pass in a new message from the command line without prompting the default editor using the -m option as follows:

$ git commit --amend -m "an amended commit message"

Changing committed files

Suppose you modified some files that you want to include in the same commit (same snapshot), but unfortunately, you forgot to add one of the files the first time around. The solution consists of staging the other file and committing using the --amend flag.

$ git commit --amend --no-edit

The --no-edit flag above will permit you to amend your commit without changing its commit message.


Avoid amending public commits

The amended commits are actually new commits. After amending a commit, the previous one will no longer be on your current branch. It has the same consequences as using the git reset in commits that are already published to a shared repository. So avoid amending commits that others have based their work on.

Note: Avoid amending commits that are already pushed to a public shared repository. Amending public commits puts developers in a confusing situation, which makes it complicated to recover from.


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.