How to edit past commit messages, not only previous one.

How to edit past commit messages, not only previous one.

$ git commit --amend -m is not the solution.

·

2 min read

At my work, I was assigned to a new project and tried to push my commits to the repo for the first time.

I was excited about it.

$ git push

And I got this error: [rejected] error: failed to push some refs to

Yes, I got denied...

That was because my project team has a certain rule that every time I push to a repo, I needed to add an issue number for every commit message. And I didn't know about it.

Until that time, I only knew about editing the last commit message by hitting
$ git commit --amend --no-edit. But this is not the case.

The Solution:

For going back to the previous commit message, you need to use this command:
$ git rebase --interactive

To demonstrate this, I created a sample project which has 4 commits as below. Let's edit the third commit message with the commit #: 014856c06a23d69d9ea3b974ec3d3161e5815b2c.

screenshots_11.45.png

1.$ git rebase --i HEAD~3

Hit $ git rebase --i HEAD~3 in the terminal for going back through three previous commits history. screenshots_.54.png

2.Hit i to switch to edit mode

After seeing the screen as above, hit i for an edit mode in vim. so you can edit the message. Change "pick" for the the commit #: 014856c06a23d69d9ea3b974ec3d3161e5815b2c to "edit".

screenshots_27.png

Hit etc to exit from the edit mode and hit :wq to save and quit.

screenshots_6.38.png

3.$git commit --amend -m "" to change the commit message.

In this case, I want to add an issue number after the message as below.
$git commit --amend -m "changed background to green #1234"

screenshots_44.png

Hit $git logand check the previous commit message has been changed to the new one as below.

screenshots_7.16.png

4.$git rebase --continue to finish the process.

It's not quite done until you run $ git rebase --continue. After running the command, check the commit history by hitting $ git log so you can see the commit history has been overwritten.

screenshots_26.png *Warning
If you've already pushed the commits to the remote repository that your teammates work with, you should avoid using $git rebase.

This useful $git rebase --interactive command also can be used for squashing and even removing commits.

I hope this helps someone who's trying to edit past commit messages.