Writing clear, meaningful commit messages is a vital part of good version control practice. But what if you make a typo, forget to add context, or need to reword a message? Fortunately, Git makes it easy to edit commit messages, whether it’s your most recent commit or one further back in your history.
In this post, we’ll cover several ways to edit commit messages safely and effectively.
✍️ Why Edit a Commit Message?
Here are some common reasons for editing a commit message:
- Fix a typo or grammatical error
- Clarify the purpose of a commit
- Add missing issue references (e.g.,
#123
) - Conform to your team’s commit message conventions
🔄 Edit the Most Recent Commit Message
If you just made a commit and want to update its message:
git commit --amend
This opens your default text editor (like Vim or VS Code) with the current message pre-filled. Update the message, save, and close the editor.
⚠️ Important: If you’ve already pushed this commit to a shared remote, you must force-push:
git push --force
Example:
git commit --amend -m "Fix typo in README instructions"
🕰️ Edit an Older Commit Message (Interactive Rebase)
To change a commit message that’s not the latest, use interactive rebase.
Step-by-Step:
- Start an interactive rebase:
git rebase -i HEAD~n
Replacen
with the number of commits back you want to review. For example, to go back 3 commits:git rebase -i HEAD~3
- A list of recent commits will appear in your text editor:
pick abc123 Commit message one pick def456 Commit message two pick ghi789 Commit message three
- Change
pick
toreword
for the commit(s) you want to edit:pick abc123 Commit message one reword def456 Commit message two pick ghi789 Commit message three
- Save and close the file.
- Git will pause and let you edit the message of the selected commit(s). Modify the message, save, and continue the rebase.
⚠️ Force-push required if the commits have been pushed to a remote:
git push --force
❌ Cancel a Rebase (if Needed)
If you run into problems or change your mind mid-rebase:
git rebase --abort
This cancels the rebase and restores your branch to its previous state.
🛡️ Best Practices
- Never rebase public/shared branches unless necessary: It rewrites history, which can confuse collaborators.
- Amend only if you haven’t pushed: It’s safe to amend unpushed commits.
- Use meaningful commit messages: Write them as if someone else (or your future self) will read them.
✅ Summary
Task | Git Command |
---|---|
Edit most recent commit | git commit --amend |
Edit older commits | git rebase -i HEAD~n |
Cancel a rebase | git rebase --abort |
Force-push after history edit | git push --force |