Amend Multiple Commit Messages with Git

Today my pair and I were about to push multiple commits when I realized we had forgotten to add the story number to all of the commit messages. Basically when I was looking at my git log:

git log --oneline

I would see something like the following.

e16f24e Fourth Commit
b4bbd67 Third Commit
57a2ca3 Second Commit
3790b98 First Commit

Our usual convention is to add the story number to the commit message. I knew that I could amend a single commit with ‘git commit –amend’, but I’ve never had to rewrite the git history like this.

To do this, we need to do an interactive rebase.

git rebase -i HEAD~5

Git will now show you the commits you specified – the last 5 in my case – in reverse order.

pick a8b8553 Previous commit message
pick 3790b98 First Commit
pick 57a2ca3 Second Commit
pick b4bbd67 Third Commit
pick e16f24e Fourth Commit

You now need to specify the commits you wish to edit – in my case this was the last four commits.

pick a8b8553 Previous commit message
e 3790b98 First Commit
e 57a2ca3 Second Commit
e b4bbd67 Third Commit
e e16f24e Fourth Commit

Git will now step through each of the commits you specified and ask you to make your changes.

Stopped at 3790b98... First Commit
You can amend the commit now, with

        git commit --amend

Once you are satisfied with your changes, run

        git rebase --continue

In my case I simply needed to amend each commit to change the commit message.

git commit --amend

After the message is changed you need to tell git to continue.

git rebase --continue

Do this for each commit and your history is rewritten!

90644d6 [Story #15] Fourth Commit
87006ff [Story #15] Third Commit
83de86b [Story #15] Second Commit
d35b899 [Story #15] First Commit

Happy coding.