How to Modify Git Commit Messages
Git provides two ways to modify commit messages, depending on the scenario. Here's a complete guide:
一、Most Common: Modify the Last Commit Message
Use case: Just committed, noticed a typo in the message, haven't pushed to remote yet.
Command
bash
git commit --amendSteps
- Run the command, and Git will open your default editor
- Modify the first line (the commit message)
- Save and exit
- Vim: Press
ito edit → make changes → pressEsc→ type:wqand Enter
- Vim: Press
One-liner (skip editor)
bash
git commit --amend -m "New commit message"二、Advanced: Modify Historical Commit Messages
Use case: Need to modify a commit that's not the most recent one.
Steps
- View commit history to find the parent commit hash of the target commit:bash
git log - Run interactive rebase (replace
commit-idwith the parent hash):bashgit rebase -i commit-id - In the editor, change
picktorewordfor the commits you want to modify - Save and exit, Git will prompt you to edit each marked commit's message
- Rebase completes automatically when done
⚠️ Important Warnings (Must Read)
1. If commit has already been pushed to remote
- You must force push to overwrite:bash
git push --force-with-lease - NEVER force push on public/team branches - it will overwrite others' work!
2. Best Practices
- Only modify history on your private branch that hasn't been pulled by others
- Use
--force-with-leaseinstead of--forcefor safer force pushes
Bonus: Modify Commit Author
Change author info without editing the message:
bash
git commit --amend --author="Shing Rui <[email protected]>" --no-editFor historical commits, use interactive rebase with edit instead of reword, then:
bash
git commit --amend --author="New Author <[email protected]>" --no-edit
git rebase --continueSummary
| Scenario | Command |
|---|---|
| Modify last commit | git commit --amend |
| Modify historical commits | git rebase -i <parent-commit-id> |
| Force push after modification | git push --force-with-lease (private branches only) |
| Change commit author | git commit --amend --author="Name <email>" |
Remember: Rewriting Git history is powerful but dangerous. Always be cautious when modifying commits that have been shared with others.