How to Correct a Commit Message in Git: A Step-by-Step Guide

As developers, we often find ourselves in a situation where we need to correct a commit message after it has already been made.

Whether it’s a typo, an incomplete message, or a change in the code's context, editing a commit message is a common requirement. Here’s a guide on how to do it effectively.

Editing the Most Recent Commit

The Simple Case - Unpushed Commit:
If you have just committed your changes and haven't pushed them to the remote repository, correcting the commit message is straightforward. You can use the --amend option in Git:

git commit --amend -m "New commit message"

This command opens your default text editor, where you can modify the commit message. Save and close the editor to complete the amendment.

If You've Already Pushed:
If you've already pushed your commit to a remote repository, you can still use the --amend option, but you'll need to force push the commit:

git commit --amend -m "New commit message"
git push --force-with-lease origin your-branch-name

The --force-with-lease option is safer than --force as it checks if the remote branch has updates you don’t have locally.


Editing an Older or Specific Commit

If you need to change a message for a commit that's further back in your history, you will need to use an interactive rebase:

  • Start the Interactive Rebase:
    First, identify how many commits back you need to go. For example, to edit a commit that's three commits back, use:
git rebase -i HEAD~3
  • Mark the Commit for Rewording:
    Your default text editor will open with a list of the last three commits. In front of the commit you want to change, replace pick with reword (or just r).
  • Reword the Commit:
    Save and close the editor. Git will then reopen the editor for that specific commit. Change the commit message as needed.
  • Complete the Rebase:
    Save and exit the editor. Git will apply the new commit message and finish the rebase.
  • Force Push if Necessary:
    If these commits have already been pushed to a remote repository, you will need to force push them as well.
git push --force-with-lease origin your-branch-name


Caution!

  • Impact on Collaborators: If you're working in a team, force pushing rewritten history can cause issues for your collaborators. It's crucial to communicate these changes with your team.
  • Avoid Rewriting Public History: As a best practice, avoid rewriting the history of public branches that other people are working on.

Subscribe to GIT.WTF!?!

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe