Let’s say you made an error in naming your commit and you would like to change it. Git offers a few ways to do it. We are going to discuss them one by one.
Option 1: Don’t change it
I know that you want things to be perfect, but there are valid reasons to let the commit be as it is.
If you already pushed your work can create new issues. Changing a commit message can cause problems for other contributors who have already pulled the original commit. If you need to change a commit message that has already been pushed, make sure to communicate with your team and coordinate your changes. Force push is needed to update the commit history in the remote repository with your updated commit message. You have to be careful, as force push can overwrite other people’s work and cause conflicts. Always communicate with your team before using a force push.
If the commit you are working on is on the local branch or you work alone, then you can consider other options.
Option 2: git commit —amend
Ammend is a relatively simple command. It allows you to update the commit message of the last commit.
Just type this command in your terminal:
git commit --amend
It will open a text editor, where you can change the commit message. Save it and viola! Job done.
I use it rarely as its use is limited to the last commit only. Therefore option 3.
Option 3: git rebase -i
Git rebase is one of my favorite git tools as it lets you cleanly rewrite history. It’s overkill when it comes to changing the last commit message, but it can be done with this command:
git rebase -i
This will open the editor with something like this:
pick d56ec13 Bad commit message # Rebase 8686af0..d56ec13 onto 8686af0 (1 command) # # Commands: # p, pick <commit> = use commit # r, reword <commit> = use commit, but edit the commit message # e, edit <commit> = use commit, but stop for amending
reword) if you wish to change the message, then send a file. It will open next editor - identical to amend.
If the commit is an older one you can dig into it with:
git rebase -i HEAD~<n>
<n> is the
n last commits you would like to revisit. That way you can reword older commits. In general,
git rebase -i is way more powerful and I highly recommend getting familiar with it.
In conclusion, changing a commit message in Git is possible, but it requires careful consideration and communication with your team. Options such as
git commit --amend and
git rebase -i offer simple and powerful ways to update commit messages, but it’s important to use them wisely and with caution. By improving your commit message hygiene, you can make your Git workflow more efficient and effective.