In this post, we will see step by step how to change older git commit messages with the help of rebase -i git command.
Quick and Important Notes
If you want to change the last commit, then you can easily change your commit message using --ammend option like this:
Another thing to note is, if you have already pushed your commit to the remote repository and making these changes, then you have to force push git push -f to replace remote commit, which can also remove other commits from the remote repo, if you are working on the team, so be careful before executing these commands.
git commit --amend -m "your new commit message goes here"
This command will change your recent last commit. But if your commit message is an old commit message then read further.
check the position of your commit
First, find the position of your commit message that you want to change.
git log --oneline
Let's say commits look like this:
704a4d0 (HEAD -> master) third commit
f67ecc5 second commit
7d85495 wrong commit message
e6dd453 Add readme
And from the above git commits we want to change the 7d85495 wrong commit message.
Interactive Rebase
git rebase -i HEAD~n command will Open your default editor, in my case neovim and also displays a list of last n commits.
git rebase -i HEAD~4
will generate output similar to:
pick 7d85495 wrong commit message
pick f67ecc5 second commit
pick 704a4d0 third commit
As you can see rebase command provided pretty good comments with what different actions you can take. In our case, we want to correct wrong commit message so we need to replace the word pick with reword and then also change the message as we like.
reword 7d85495 wrong commit message
pick f67ecc5 second commit
pick 704a4d0 third commit
...
And finally, save the changes and exit, for vim editor we can do :wq.
Now rebase will ask you to edit your commit message, here you can put the correct message, I will write Correct commit message in my example:
Correct commit message
save and exit your editor again
Confirm your changes
git log --oneline
should output similar to:
10d13bb (HEAD -> master) third commit
7b200bb second commit
92073a4 Correct commit message
e6dd453 Add readme
And you should see the correct commit message
Force push
If you changed the commit message after it was already pushed to your remote git repository, then you have to force-push your changes because your commit hash is already changed.
In our case old commit hash was 7d85495 and the new commit has is 92073a4
git push origin <branch-name> -f