Trusted answers to developer questions

How to change a Git commit message after a push

Educative Answers Team

Grokking the Behavioral Interview

Get Educative’s popular interview prep course for free.

Commits to Git are accompanied with a commit message that explains what changes the commit has made to the code. However, a situation may arise where the commit message will need to be changed after it has been pushed. ​

svg viewer

Changing the latest Git commit message

If the message to be changed is for the latest commit to the repository, then the following commands are to be executed:

  1. git commit --amend -m "New message"
  2. git push --force repository-name branch-name

Note that using --force is not recommended unless you are absolutely sure that no one else has cloned your repository after the latest commit.

A safer alternative is to use:

git push --force-with-lease repository-name branch-name

Unlike --force, which will destroy any changes someone else has pushed to the branch, --force-with-lease will abort if there was an upstream change to the repository.

Changing older commit messages

If the message needs to be amended for an older commit, then the interactive rebase tool can be used:

  1. Navigate to the repository that contains the commit you want to amend and open a terminal window.
  2. Use the git rebase -i HEAD~n command to display a list of the last nn commits in your default text editor. For example, the following command would display a list of the last three commits in your current branch:
    git rebase -i HEAD~3 

The list would be similiar to this:

pick e499d89 Delete CNAME
pick 0c39034 Better README
pick f7fde4a Change the commit message but push the same commit.

# Rebase 9fdb3bd..f7fde4a onto 9fdb3bd
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# These lines can be re- ordered; they are executed from top to
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
# Note that empty commits are commented out
  1. Replace pick with reword before each commit message that needs to be changed:
    pick e499d89 Delete CNAME
    reword 0c39034 Better README
    reword f7fde4a Change the commit message but push the same commit.
  2. Save and close the commit list file.
  3. In each resulting commit file, type the new commit message, save the file, and close it.
  4. Force push the amended commits using git push --force.


Trusted Answers to Developer Questions

Related Tags

Keep Exploring
Related Courses