Do you need to make Git to change a commit message either in the the last commit, or quite a few commits? And what about those you’ve already pushed to the remote repository? And how quickly can this be fixed before someone sees the swear word you forgot to take out?
In these examples, your remote repository is called origin, as is the convention, and the commit you want to change is on a branch called my-branch. Let's dive in and see how to make Git amend a commit message.
The Solution to Change the Latest Commit Message
This immediately alters the message, requiring no confirmation:
git commit --amend -m "Added the new feature without swearing"
Or this opens an editor to write a multi-line/formatted message:
git commit --amend
Optional: To specify an editor for Git to open, type in something like this, always using forward slashes, even on Windows:
Finally, this pushes all your changes to the remote branch. (Using -f is the same as --force) Warning: You will lose all commits on the remote branch that aren’t in the local repository, so check first. And the commit you altered will have a new SHA (hash), which could cause problems for colleagues who are using this branch, if you have pushed that commit already.
git push origin my-branch -f
The Solution to Change Multiple Commit Messages
In this example, we’re trying to change the message in 3 of the last 5 commits.
This opens up your selected text editor for interactive rebasing:
git rebase -i HEAD~5
When the editor has opened, as shown in the example below, replace pick with reword next to the commits you wish to amend. Then close the editor to start the rewriting process.
pick 975de9e feat(World Peace): started dealing with problems reword 9958258 feat(World Peace): tried to force world peace reword 5c428a2 feat(World Peace): added in some possible solutions pick ca34dd6 feat(World Peace): removed 2 solutions reword fc273f4 feat(World Peace): added the Greta Thunberg solution
# Rebase 1c8f5e0..fc273f4 onto ca34dd6 (5 commands) # # Commands: # p, pick = use commit # r, reword = use commit, but edit the commit message # e, edit = use commit, but stop for amending # s, squash = use commit, but meld into previous commit # f, fixup = like "squash", but discard this commit's log message # x, exec = run command (the rest of the line) using shell # b, break = stop here (continue rebase later with 'git rebase --continue') # d, drop = remove commit # l, label
You can now change the message of each commit in turn, following the process as instructed.
GitBreeze is an effortless Git GUI that's free for use at work, at home, anywhere. It boosts software development. It works on Windows, macOS, and Linux.