How to Change a Commit Message in Git…

Tharuja Sandeepanie
4 min readDec 1, 2019

--

By this article , let’s see how to change a commit message in Git ..Sometimes due to the incorrect commit messages, you may have found yourself in a situation where you want to edit a commit message. 😩 Your commit may be a most recent or a very old one, or may be already pushed or may not. However, let’s see how to change your commit message for all of these scenarios one by one 😉

A) Changing the most recent and not pushed commit message

If you haven’t pushed your commit to remote repository yet, simply type following command to change your most recent commit message.

git commit --amend -m "correct commit message"

or , type following command and press enter.

git commit --amend

Then your text editor will appear as shown in below and you can type the new commit message and save the commit.

( I recommend you to change your default text editor for Git into vim editor.. for Ubuntu users you can download vim editor using this link. After downloading you can configure it using the following command. )

git config --global core.editor vim

In your vim editor , press i to edit a line and after editing press esc and :wq and enter to save and close the editor .

B) Changing the most recent and pushed commit message

If you have already pushed your commit to remote repo , edit the message just like above and force push the update using below command.

git commit --amend -m "correct commit message"
git push origin <branch-name> --force

C) Changing an old and not pushed commit message

We need to do an interactive rebase to find the commit you want to correct. Type below command and it will display the last n number of commits in your text editor.

git rebase -i HEAD~n      // n is the number of commits to go back

There are two ways to change the commit message here.

  1. Simply replace the pick word with reword for the commits you want to correct the message.

Then save and close the editor and now you can correct the commit message in each resulting commit file.

Save and close the each commit file. Then your commit messages will be changed successfully.

or ,

2. Simply replace the pick word with edit for the commits you want to correct and save and close the editor.

And then you can change the commit message using following command.

git commit --amend -m "correct commit message"

And then type this to go to the next commit which you want to change the message.

git rebase --continue

Do this for each commit and finish the rebase.

Then your commit messages will be changed successfully.

In any case, if you go wrong inside the rebase , you can type below command and abort the changes in rebase.

git rebase --abort

D) Changing an old and pushed commit message

Here , you can edit the message as in part C) and then force push the updates using below command.

git push origin <branch-name> --force

Happy Coding !! 😃

--

--