场景:我push一个commit到远程仓库后发现commit message写错了,需要更改。如下图所示。我想把最新的commit "a wrong commit message" 改成 "add aaa in afile"
$ git clone git@github.com:bin9wei/test-git.git
$ cd test-git
$ echo aaa >> afile.txt
$ git add .
$ git commit -m "a wrong commit message"
$ git push
![](https://img-blog.csdnimg.cn/img_convert/47d7390cf3b0eba18ad15439942642dc.png)
git commit --amend用来修改最新commit的信息
$ git commit --amend -m "add aaa in afile"
$ git log
commit f3891d590397d3fedc82910379d4155dc72b783f (HEAD -> main)
Author: bin9wei <bin9wei@foxmail.com>
Date: Sun Feb 12 22:43:40 2023 +0800
add aaa in afile
commit 83c97556c5e64efeb0c819180117ad704383963f
Author: bin9wei <bin9wei@foxmail.com>
Date: Fri Dec 9 18:31:19 2022 +0800
add afile and bfile
commit f596f8ad426416b6ae55cb07db2e11d123da33cd
Author: bin9wei <bin9wei@foxmail.com>
Date: Fri Dec 9 15:39:24 2022 +0800
first commit
无法git push,用git push --force-with-lease,意思是强行推送到远程仓库,但如果远端有其他人推送了新的提交,那么推送将被拒绝。注意,不建议使用git push --force
$ git push
To github.com:bin9wei/test-git.git
! [rejected] main -> main (non-fast-forward)
error: failed to push some refs to 'github.com:bin9wei/test-git.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
$ git push --force-with-lease
![](https://img-blog.csdnimg.cn/img_convert/e7628b182ca7e18f4942dc607048764c.png)
参考
https://www.educative.io/answers/how-to-change-a-git-commit-message-after-a-push