修改git以往历史中所有commit的name和email

时间:2023-07-26 22:24:50

当换了新的电脑设备或者在 homestead 中使用 git 的时候;
如果忘了 git config 设置用户名和邮箱;
这样当 git commit 的时候就会使用设备名作为 git 用户名;
或者我们还可能手抖设置了错误的用户名和邮箱;
然后再一不小心推到了服务器或者 github 上后就尴尬了;
这时候就需要下面的脚本来批量修改历史 commit 中的用户名和邮箱了;
在项目跟目录下创建如下脚本文件 email.sh

#!/bin/sh

git filter-branch --env-filter '

OLD_EMAIL="your-old-email@example.com"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="your-correct-email@example.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
Bash

3.修改以下变量:

变量 描述
OLD_EMAIL 错误的或者默认的邮箱
CORRECT_NAME 正确的用户名
CORRECT_EMAIL 正确的邮箱

给执行权限;

chmod +x email.sh
Bash

执行脚本;

./email.sh
Bash

没有效果就多执行几次;
再不醒就添加新个的commit 再执行;
如果遇到如下错误 :

Cannot create a new backup.
A previous backup already exists in refs/original/
Force overwriting the backup with -f
Bash

执行如下命令;

git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch Rakefile' HEAD
Bash

然后再执行 email.sh 脚本;
如果 git push 失败就执行强制推送:

git push origin --force --all
git push origin --force --tags
Bash

force push 是极其危险的操作;
切记先提前告知同事;
否则被打个粉末性骨折都是轻的;