Trusted answers to developer questions

How to change a Git commit message after a push

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Commits to Git are accompanied by a commit message that explains what changes the commit has made to the code. However, a situation can 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: Using --force is not recommended unless we’re absolutely sure that no one else has cloned our repository after the latest commit.

A safer alternative is to use the following:

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

Unlike --force, which destroys any changes someone else has pushed to the branch, --force-with-lease aborts if there’s 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 we 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 our default text editor. For example, the following command displays a list of the last three commits in our current branch:

    git rebase -i HEAD~3 
    

The list will 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
bottom.
#
# 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.

RELATED TAGS

git
commit
change
message
push
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?