To modify the information of the most recent Git commit (including the commit message and potentially the content of files that need to be changed), and these changes should also be reflected in the remote repository.
1. Modify the message of the most recent commit#
Make sure you are currently on the local branch where you want to modify the commit message.
Use the git commit --amend
command to modify the message of the most recent commit.
After running this command, an editor will open (based on your system configuration), allowing you to modify the commit message.
Once you have made the modifications, save and close the editor.
If you want to directly specify a new commit message without opening the editor, you can use the -m
parameter.
git commit --amend -m "New message"
2. Push to the remote repository#
Since you have modified the commit history, pushing directly to the remote repository will result in conflicts.
In this case, we need to use the --force
or --force-with-lease
parameter to force the push and overwrite the corresponding commit in the remote repository.
Use --force
(not recommended)
git push --force origin <remote branch>
Using
--force
will forcefully update the remote branch to be completely consistent with your local branch state.
If there are other commits to the remote branch by others during this time, they will be overwritten by your push.
Therefore,--force
should be used with caution.
Use --force-with-lease
(recommended)
git push --force-with-lease origin <remote branch>
--force-with-lease
provides a safer way to force push.
It checks if the state of the remote branch is as expected before pushing.
If there are new commits by others to the remote branch since your last pull, the push will fail, avoiding accidentally overwriting others' work.
In collaborative development, using--force-with-lease
is a better choice.