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

Some readers pointed out some additional valuable tips I did’t know about:

  1. You can use the same technique to amend the author of the commit - git commit --amend --author "Name Goes Here". Thanks to StevenMcD for the tip!
  2. If you only want to change the commit message you can use r (for ‘reword’) rather than e (as I did in my examples). The edit option is really only intended for when you want to add or remove files from an older commit, or split one.
  3. The git interface doesn’t make this obvious, but you can also remove or reorder commits by removing or reordering the commit lines during the interactive rebase.
  4. If you do a git rebase -i without specifying a revision range you get all your unpushed commits, which is probably what you want to rebase anyways. Thanks to Simon Brunning for this tip and the previous two!

Happy coding.