Changing a commit message on Git can be necessary for several reasons, such as correcting spelling errors, adding missing information, or clarifying the purpose of the changes. However, editing commit messages, especially after they have been pushed, should be done with caution as it can affect the repository history. This guide will explain how to change commit messages in your local and remote Git repositories.
Changing the last commit message
If you need to change the message of the most recent commit that has not been pushed to Git, you can use the git commit --amend
command. This is the simplest case and does not affect other users.
Steps to amend the last commit message:
Open your terminal.
Navigate to your repository.
Run the following command:
Terminalgit commit --amend -m "New commit message"This command opens the default text editor set in your configuration, allowing you to change the commit message. Save the changes and close the editor.
Example:
If your last commit message was "Initial commit" and you want to change it to "Add initial project structure", you would use:
git commit --amend -m "Add initial project structure"
Changing a commit message after it has been pushed to Git
Warning
Changing a commit message after a push modifies the repository's history. If other collaborators have already pulled the changes, this can cause conflicts and disrupt their work.
Changing the commit message with an interactive rebase
If you need to change the message of a commit that has already been pushed or is not the latest commit, you will need to perform an interactive rebase:
Determine how many commits back you need to go.
Use the following command to start the rebase:
Terminalgit rebase -i HEAD~nReplace
n
with the number of commits you want to review.In the editor that opens, change
pick
toreword
for the commit you want to change.Save and close the editor.
Change the commit message in the new editor window that opens.
Save and close the editor to complete the rebase.
Example:
Suppose you want to change a commit message three commits back. You would start with:
git rebase -i HEAD~3
In the text editor, find the commit you want to edit, change pick
to reword
, and then save and exit. When prompted, rewrite the commit message, save, and exit again.
Pushing the changes after a rebase
After changing the commit message through rebase, you will need to push the changes to Git. Since the history has changed, you will need to use the --force
option:
git push --force
Caution
Using git push --force
can overwrite changes in the remote repository. Communicate with your team before force-pushing to avoid disrupting others' work.
For further reading see the official Git documentation.