Change Git commit messages with amend and interactive rebase

/ Jack Lot


Git gives you two ways to update a commit message that’s already been created. Which one you use depends on how far back the mistake is, and there’s a caveat worth knowing before you start.

The cheatsheet

Fixing the latest commit message

git commit --amend -m "<message>"

If the message belongs to the most recent commit, --amend replaces it with <message>.

Fixing an older commit message

git rebase -i HEAD~x

--amend only works on the latest commit, anything older needs interactive rebase. -i spawns interactive mode, and HEAD~x is how far back in history you want to reach; substitute x for whatever number of commits reaches yours.

For example: git rebase -i HEAD~5allows you to modify the previous 5 commits.

After executing, Git opens your terminal’s default editor with the commits in the specified range, each prefixed with pick. Change pick to reword in front of the commit you want to fix, then save and close.

reword 7f9d4bf Fixed the frontpage bgu
pick 3f8e810 Updated screenreader attributes

Git then stops and lets you type the corrected message.

Note: this process is somewhat difficult to explain so I recommend watching the video if you’re confused.

The caveat

Interactive rebase does not edit commits in place. It replays the changes from each commit in the range back onto your branch. All of them get new hashes, not just the one you reworded. Only do this to local changes: once commits are in a shared repository, other people may have based work on them.

Going further

Reword is one of several interactive rebase commands, along with reordering, squashing, splitting and deleting. Check techniques for rewriting Git history to explore them all.

Additionally, we dive deep into the rebase command in the rebase deconstructed course on LearnGit.io


TAGS: videos, git, tutorials