Git allows you to modify commit messages using different commands, depending on whether the commit is recent or already pushed to a remote repository.
- Change the latest commit message using amend.
- Edit older commit messages using interactive rebase.
- Additional steps required if the commit is already pushed to a remote.
Changing the Most Recent Commit Message (Not Pushed Yet)
If the commit is local and not pushed, you can update its message using the following command.
git commit --amend- Opens the default text editor with the current commit message.
- Edit the message as required.
- Save the file and close the editor to apply the changes.
Note: Ensure that you don’t have any uncommitted changes staged, as they will also be included in the amended commit.
Changing a Commit Message That Has Already Been Pushed
If the commit is already pushed, you must force-push the amended commit, which rewrites remote history-use with caution.
- Amend the commit message locally as described above.
- Force push the amended commit to the remote branch using:
git push <remote> <branch> --forceNote:
- Replace '<remote>' with the remote repository name (e.g., 'origin') and '<branch>' with the branch name
- Force-pushing rewrites the remote branch with your local state, which can cause data loss for collaborators who have already pulled the previous version of the commit.
Interactive Rebase (For Older or Multiple Commits)
If you need to update messages for multiple commits or older commits, use interactive rebase:
- Start an interactive rebase:
git rebase -i HEAD~n - Replace 'n' with the number of commits you want to go back.
- Replace pick with reword (or edit) for the commit you want to modify in the interactive editor.
- Update the commit messages as necessary and save the changes.
- Complete the rebase process by following the prompts. If you used 'edit', you will need to re-commit the changes.
Note: Be cautious when rewriting shared commit history, especially if other collaborators are working on the same branch.
Example
To change the message of the most recent commit:
- Run:
git commit --amend
- Edit the commit message in the editor that opens.
- Save and close the editor.
- If the commit was already pushed, force push it to the remote repository:
git push origin main --forceFor changing an older commit, let's say the last 3 commit:
- Run:
git rebase -i HEAD~3
- In the editor, change 'pick' to 'reword' for the commits)you want to change.
- Save and close the editor.
- Edit the commit messages as prompted.
- Force push the rebased commits:
git push origin main --forceNote: Avoid rewriting history in a shared Git repository unless necessary, and always coordinate with your team.