Git 修改已提交 commit 的信息


背景

由於 Github 和公司 Git 使用賬號不一樣,偶爾沒注意,提交出錯后就需要修改 commit 信息。

修改最后一次提交 commit 的信息

# 修改最后一次提交的 commit 信息
$ git commit --amend --message="modify message by daodaotest" --author="jiangliheng <jiang_liheng@163.com>"

# 僅修改 message 信息
$ git commit --amend --message="modify message by daodaotest"

# 僅修改 author 信息
$ git commit --amend --author="jiangliheng <jiang_liheng@163.com>"

修改歷史 commit 的信息

操作步驟:

  • git rebase -i <commit id> 列出 commit 列表
  • 找到需要修改的 commit 記錄,把 pick 修改為 edite:wq 保存退出
  • 修改 commit 的具體信息git commit --amend,保存並繼續下一條git rebase --continue,直到全部完成
  • 中間也可跳過或退出git rebase (--skip | --abort)
# 列出 rebase 的 commit 列表,不包含 <commit id>
$ git rebase -i <commit id>
# 最近 3 條
$ git rebase -i HEAD~3
# 本地倉庫沒 push 到遠程倉庫的 commit 信息
$ git rebase -i

# vi 下,找到需要修改的 commit 記錄,```pick``` 修改為 ```edit``` 或 ```e```,```:wq``` 保存退出
# 重復執行如下命令直到完成
$ git commit --amend --message="modify message by daodaotest" --author="jiangliheng <jiang_liheng@163.com>"
$ git rebase --continue

# 中間也可跳過或退出 rebase 模式
$ git rebase --skip
$ git rebase --abort

批量修改歷史 commit 信息

創建批量腳本changeCommit.sh

$ cat changeCommit.sh
#!/bin/sh

git filter-branch --env-filter '

# 之前的郵箱
OLD_EMAIL="jiangliheng@126.com"
# 修改后的用戶名
CORRECT_NAME="jiangliheng"
# 修改后的郵箱
CORRECT_EMAIL="jiangliheng@163.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

執行腳本成功后,強制推送到遠程服務器:

$ git push --force --tags origin 'refs/heads/*'

微信公眾號:daodaotest


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM