In Git, it's common to make mistakes when writing commit messages, but don't worry, you can modify an existing, unpushed commit message. In this tutorial, we will cover two methods for doing this: amending the most recent commit message and performing an interactive rebase.
If you need to change the most recent commit message, use the git commit --amend
command. This command will open your text editor, allowing you to change the commit message of the most recent commit. You can also set the commit message directly in the command line with git commit --amend -m "New commit message"
, but this can make multi-line commit messages or small corrections more cumbersome to enter.
Make sure you don't have any working copy changes staged before doing this, or they will get committed too. Unstaged changes will not get committed.
Another option is to use interactive rebase. This method allows you to edit any message you want to update, even if it's not the latest message.
Determine the number of commits you want to update. Let's call this n
.
Run git rebase -i HEAD~n
. This will open your text editor with a list of all commits since the one you gave.
Change pick
to reword
(or on old versions of Git, to edit
) in front of any commits you want to fix.
Once you save, Git will replay the listed commits.
For each commit you want to reword, Git will drop you back into your text editor. For each commit you want to edit, Git will drop you into the shell.
Change the commit message in any way you like.
Run git commit --amend
.
If you're in the shell, run git rebase --continue
.
Note that this method may modify the commit ID, so be cautious about amending commits that you have already shared with other people. Amending commits essentially rewrites them to have different SHA IDs, which poses a problem if other people have copies of the old commit that you've rewritten. Anyone who has a copy of the old commit will need to synchronize their work with your newly re-written commit, which can sometimes be difficult, so make sure you coordinate with others when attempting to rewrite shared commit history or just avoid rewriting shared commits altogether.
Now you know how to modify existing, unpushed commit messages in Git. Remember to use these methods with caution, and always coordinate with others when rewriting shared commit history.