(the post is automatically translated by AI)
Introduction
When using Git [1] for version control, it’s easy to accidentally make a typo in a commit message — or simply realize later that it could be worded better. In those cases, you need to go back and fix the commit message.
The basic approach is git commit --amend [2], which corrects the most recent commit message. In this article, I’ll document how to go back to an older commit — not just the last one — and edit its message for future reference.
Problem Scenario
Suppose the first five commits added files a, b, c, d, and e. However, as shown below, the third commit message accidentally says Add d.txt instead of Add c.txt:
git log --oneline
13d43cf (HEAD -> master) Add e.txt
72dc4bd Add d.txt
20f1770 Add d. txt ← should be "Add c.txt"
899c8fa Add b.txt
383b0b Add a. txt
Since HEAD is already at 13d43cf, we can’t use git commit --amend directly to fix 20f1770.
How do we edit the commit message of 20f1770?
Solution
We’ll use git rebase in interactive mode [3], triggered with the -i or --interactive flag. To modify commit 20f1770, we need to rebase starting from the commit before it.
Steps:
- Run this command in the terminal:
git rebase -i 899c8fa # the commit before the one you want to edit
- A list like this will appear:
pick 20f1770 Add d.txt
pick 72dc4bd Add d.txt
pick 13d43cf Add e.txt
# Rebase 899c8fa..13d43cf onto 899c8fa (3 commands)
# ...
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# ...
- Change
picktoeditfor the commit you want to modify:
edit 20f1770 Add d.txt
pick 72dc4bd Add d.txt
pick 13d43cf Add e.txt
Save and exit (
Esc+:wq)Use
--amendto edit the message:
git commit --amend
- Change the message:
Add c.txt
# Changed from "Add d.txt" to "Add c.txt"
Save and exit (
Esc+:wq)Continue the rebase:
git rebase --continue
- Done! Running
git log --onelinenow shows:
6ff9253 (HEAD -> master) Add e.txt
155afa9 Add d.txt
93c8fff Add c.txt
899c8fa Add b.txt
38e3b0b Add a.txt
Conclusion
In this article, I documented how to edit older commit messages, including commits several steps back. The key tools are:
git rebase -igit commit --amend
Used together, they let you cleanly rewrite any past commit message.
References
- Git - https://git-scm.com
- git commit –amend - https://git-scm.com/docs/git-commit#Documentation/git-commit.txt---amend
- Interactive mode - https://git-scm.com/docs/git-rebase#_interactive_mode