Karp 的技术博客

两种情况:

1.已经将代码push到远程仓库
2.还没将代码push到远程仓库,还在本地的仓库中

这两种情况下的修改大体相同,只是第一种情况最后会多一步
下面来说怎么修改

先搞清楚你要修改哪次的提交注释或者哪几次的提交注释

修改最后一次注释

如果你只想修改最后一次注释(就是最新的一次提交),那好办:

git commit --amend

出现有注释的界面(你的注释应该显示在第一行), 输入i进入修改模式,修改好注释后,按Esc键 退出编辑模式,输入:wq保存并退出。ok,修改完成。
例如修改时编辑界面的图:

photo_2024-05-02 15.52.08.jpeg

修改之前的注释

修改之前的某次注释

  1. 输入:

    git rebase -i HEAD~2

    最后的数字2指的是显示到倒数第几次 比如这个输入的2就会显示倒数的两次注释(最上面两行)

 git rebase -i HEAD~2         
hint: Waiting for your editor to close the file... 
pick 36bceb83c [test] 测试2
pick c68574f7b [test] 测试1

# Rebase 01c82d86d..c68574f7b onto 01c82d86d (4 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup [-C | -c] <commit> = like "squash" but keep only the previous
#                    commit's log message, unless -C is used, in which case
#                    keep only this commit's message; -c is same as -C but
#                    opens the editor
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
#         create a merge commit using the original merge commit's
#         message (or the oneline, if no original merge commit was
#         specified); use -c <commit> to reword the commit message
# u, update-ref <ref> = track a placeholder for the <ref> to be updated
#                       to this position in the new commits. The <ref> is
#                       updated at the end of the rebase
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.

  1. 你想修改哪条注释 就把哪条注释前面的pick换成edit。方法就是上面说的编辑方式:i---编辑,把pick换成edit---Esc---:wq.
  2. 然后:(接下来的步骤Terminal会提示)

    git commit --amend
  3. 修改注释,保存并退出后,输入:

    git rebase --continue

photo_2024-05-02 15.54.03.jpeg

其实这个原理我的理解就是先版本回退到你想修改的某次版本,然后修改当前的commit注释,然后再回到本地最新的版本

修改之前的某几次注释

修改多次的注释其实步骤和上面的一样,不同点在于:

  1. 同上
  2. 你可以将多个想修改的commit注释前面的pick换成edit
  3. 依次修改你的注释(顺序是从旧到新),Terminal基本都会提示你接下来的操作,每修改一个注释都要重复上面的3和4步,直到修改完你所选择的所有注释

已经将代码push到远程仓库

首先,你把最新的版本从远程仓库先pull下来,修改的方法都如上,最后修改完成后,强制push到远程仓库:

git push --force origin master

注:很重要的一点是,你最好保证在你强制push之前没有人提交代码,如果在你push之前有人提交了新的代码到远程仓库,然后你又强制push,那么会被你的强制更新覆盖!!!

最后,可以检查一下远程的提交记录~~

git

版权属于:karp
作品采用:本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
更新于: 2024年05月02日 07:55
4

目录

来自 《Git 修改已提交的commit注释》
774 文章数
0 评论量
9 分类数
779 页面数
已在风雨中度过 9年277天3小时25分