Messing up your commit message is something that happens every now and then. Git allows you to make changes to your last commit by using the
$ git commit --amend
This will open the default editor that you configured with the message of your previous commit. In here you just change the message and exit out your editor. And voilà, commit message changed.
You can use the
-m option as well, to set the message directly from the command line.
$ git commit --amend -m "Hold your horses, bugfix incoming"
Be aware that
--amend adds the changes you staged to the commit. So if this is not desired you need to either unstage the changes or stash them for the time being.
If you have pushed the commit to a remote before and try to push again, Git will reject your push. In that case you need to use
git push --force. You need to be careful with this. Using
--force overwrites the history of your remote. Also, if others already based their work on your commit they might not be happy.
You might have noticed that the timestamp of the commit didn’t change. If you want to update the timestamp too, you can set the
GIT_COMMITTER_DATE environment variable before running the command.
GIT_COMMITTER_DATE="Wed Apr 03 15:00 2020 +0100" git commit --amend
If the commit message you want to change isn’t from the last commit things get more tricky. The easiest way I found is using an interactive rebase. Find the commit hash of the commit before the one you’d like to change.
git rebase -i 9bef4f8
In the editor that opens, change the
pick command for
edit for the commit you want to change.
edit 9e48a07 %$#^$% pick 2142d46 Perfect... pick 10da46d Hacky code, might be buggy pick 5ba932b Hold your horses, bugfix incoming # Rebase 9bef4f8..5ba932b onto 5ba932b (4 commands) # # Commands: # ...
You are now in the past. You can make changes on top of commit
9e48a07. Or… just change the commit message. We will do that for now.
$ git commit --amend -m "Enjoy your code, Sir"
Now that we changed the message we need to rebase the commits that came next on this new change.
$ git rebase --continue
So, did that work? Lets find out.
$ git log --abbrev-commit --pretty=oneline 5ba932b (HEAD -> master) Hold your horses, bugfix incoming 10da46d Hacky code, might be buggy 2142d46 Perfect... 9e48a07 Enjoy your code, Sir 9bef4f8 We will need to rebase from here
As you can see, the commit message has changed. As well as the commit hash. If you find yourself amending more ofter, consider adding an alias in your gitconfig.
[alias] amend = commit --amend