Git批量修改commit中的user.name和user.email

594 阅读1分钟

背景

相信更多小伙伴在初始化 git 仓库时没有设置仓库的 user.name、user.email 而导致 commit 错误的用户和邮箱的情况。如何批量的对所有的commit进行修改是个问题。

目标

  1. 设置本地某一仓库的 user.name 和 user.email.
  2. 设置本地所有仓库的 user.name 和 user.email.
  3. 修改已提交commit的 user.name 和 user.email.

办法

1.设置本地某一仓库的 user.name 和 user.email.

本环节 name 和 email设置,只对本仓库有效。

git clone https://yourRepo.git
cd yourRepo
git config username "YourName"
git config username "YourEmail@domain.com"

2.设置本地所有仓库的 user.name 和 user.email.

本环节 name 和 email设置,对git管理的所有仓库有效。

git clone https://yourRepo.git
cd yourRepo
git config --global username "YourName"
git config --global username "YourEmail@domain.com"

3. 修改已提交commit的 user.name 和 user.email.

首先,确认如下信息

OLD_EMAIL = "your_old_email@domain.com"

CORRECT_NAME = "your_correct_name"

CORRECT_EMAIL = "your_correct_email@domain.com"

再次,按照上述信息,修改脚本,粘贴入终端

% git filter-branch --env-filter '
OLD_EMAIL="your_old_email@domain.com"
CORRECT_NAME="your_correct_name"
CORRECT_EMAIL="your_correct_email@domain.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

最后,按 Enter 键执行脚本,并同步到远程仓库

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