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:
I would see something like the following.
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 will now show you the commits you specified – the last 5 in my case – in reverse order.
You now need to specify the commits you wish to edit – in my case this was the last four commits.
Git will now step through each of the commits you specified and ask you to make your changes.
In my case I simply needed to amend each commit to change the commit message.
After the message is changed you need to tell git to continue.
Do this for each commit and your history is rewritten!
Some readers pointed out some additional valuable tips I did’t know about:
- 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! - If you only want to change the commit message you can use
r
(for ‘reword’) rather thane
(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. - 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.
- 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.