Updating Old Git Commit Messages

Content:

Looking back through your Git commit history, you might find that some of your commit messages leave a lot to be desired.

Writing good commit messages can be surprisingly difficult, and it can be all too easy to get into bad habits when writing your messages. This is particularly true when creating projects on your own – there’s nobody else trying to understand your code.

If you’re looking to improve your old messages, Git does provide a mechanism to do this. Be warned, though, there are a few things to consider before deciding to make this change.

What Git Will Change

Before going further, consider whether your code has been made publicly available through a site such as GitHub. Changing your commit messages will rewrite your commit history, impacting any projects forked from your code.

Along with rewriting commit messages, commit dates will also be updated. It’s possible to put these back as well, though it’s a lot of extra work and wont be covered in this article.

It’s also a rather manual process – only consider this with a small project, or one where only a few recent commits need amending.

With that said, lets start changing our commit messages.

Changing Your Messages

The first step is to count the number of commits you need to step back through to get to the oldest commit you want to change. You’ll need to use this value to in the following command.

git rebase -i HEAD~n

replace n with the number of comments to go back through. For example, if the oldest commit to change is the 3rd-newest, the command would be

git rebase -i HEAD~3

You’ll then be presented a list of commits from the point you’ve chosen.

pick a8dc5e9 Add a feature
pick acf6fdb Update docs
pick 6162072 Delete old code

For each of the commits listed, change pick to r (or reword) for any commits whose message you want to update.

r a8dc5e9 Add a feature
pick acf6fdb Update docs
r 6162072 Delete old code

Here, we’ll be keeping the second commit message, but updating the other two. Save the file and exit to continue.

You’ll now be presented with each commit message in turn. Update the message, and save it once you’re done.

That’s all there is to it. Your commit messages should now have changed.

Pushing Changes to Remote

If you’ve pushed the code to an online system, such as GitHub, you’ll want to push the new messages to your repo. Consider again the impact this will have if your repo is public before doing this.

As you’ll be rewriting the history on the remote repo, you’ll need to run git push with the --force parameter. Don’t forget to include your remote repo name (usually origin) and branch name (often either master or main for the primary branch).

git push origin master --force

Your repo should now match your local repo, with updated commit messages.