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.
If the message to be changed is for the latest commit to the repository, then the following commands are to be executed:
git commit --amend -m "New message"
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.
If the message needs to be amended for an older commit, then the interactive rebase tool can be used:
Navigate to the repository that contains the commit we want to amend and open a terminal window.
Use the git rebase -i HEAD~n
command to display a list of the last 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
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.
git push --force
.RELATED TAGS