How to Change Git Commit Messages Using Amend

Every Git commit must be accompanied by a message used to describe the work completed. Whether a simple description of changes or a link to a Agile story, it provides a reference to easily allow other developers to indentify what changes were made to the code.

Being human we all make mistakes and sometimes that means we make an error in our Git commit messages. In this tutorial we will learn how to update previous commit messages.

Commiting Changes with Git

Let’s start of by creating a simple commit to our project’s Git repository.

git commit -m "Refactor user comment class"

Updating the most recent Git Commit Message

If you discover an error in your most recent Git commit message, use the following command to change it.

git commit --amend

A new text editor will open which will allow you to modify the commit message. Save your changes and exit to the text editor to apply your new commit message.

Changing a Previous Git Commit Message

To amend the commit message of a previous Git commit, the process is slightly more complicated than amending your previous commit. You will need to identify the exact commit to amend using the rebase command. We can do this by choosing the commit relative to HEAD.

git rebase -i HEAD~n

For example, to change the commit message of commit two commits behind your most recent commit, we would do the following

git rebase -i HEAD~3

Pushing Amended Commits

Amending a commit in your local repository is simple and low risk. Complications are introduced by amending commits already publicly shared.

To push an amended commit to a public repository you will need to use the force argument. Doing so instructs the hosted repository to overwrite its existing history to include the amendments.

git push --force