You can programmatically edit only the last commit message:
git commit --amend -m 'xxxxxxx'
Or a random commit interactively:
git rebase -i HEAD~n
# Vim opens up, select the commit you want to modify, and change the word "pick" for "edit"
git commit --amend -m "Changing an old commit message!"
git rebase --continue
How do I combine both? I want to change a message programmatically, but to a prior commit, not just the last one.
The commit I want to modify has already been pushed to a git server, but having other people re-sync the git project is not a concern.
To change the most recent commit message, use the git commit --amend command. To change older or multiple commit messages, use git rebase -i HEAD~N .
The git commit –amend command lets you modify your last commit. You can change your log message and the files that appear in the commit. The old commit is replaced with a new commit which means that when you amend your old commit it will no longer be visible in the project history.
The reason you can not simply "amend" an arbitrary commit is that commits are immutable. When you amend a commit, it actually replaces the current commit with another and moves your branch to the new commit. The commit with the old message, author name, etc. is still there in the history until you clean it up:
Before:
master
|
v
A -- B -- C
After:
master
|
v
A -- B -- C'
\
\- C
To simulate "amending" an arbitrary commit, you would have to rewrite not only that commit, but the entire history after it, since a commit includes its parents as part of its immutable data:
Before:
master
|
v
A -- B -- C
After:
master
|
v
A -- B' -- C'
\
\- B --- C
You can do this by creating a branch on the commit you are interested in, amending it, and rebasing the range of commits following the original to the tip of your original branch onto the new branch. Here is an example showing what you are after:
Start:
master
|
v
A -- B -- C -- D
New Branch:
master
|
v
A -- B -- C -- D
^
|
temp
Amend:
master
|
v
A -- B -- C -- D
\
\- B'
^
|
temp
Rebase:
A -- B -- C -- D
\
\- B' -- C' -- D'
^ ^
| |
temp master
Cleanup:
A -- B -- C -- D
\
\- B' -- C' -- D'
^
|
master
This is pretty much exactly what interactive rebase does when you only modify a single commit, by the way, except without the explicit temporary branch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With