修改git提交的名字和邮箱

由于有些规定,要保密个人信息,只能通过这种方法来把个人信息给过滤掉。

修改OLD_EMAIL为要替换的旧邮箱,NEW_NAMENEW_EMAIL为新的个人名字和邮箱,修改完成后强制更新到服务器。

这样只能一个人一个人的修改,其他人重新克隆仓库,如果要修改文件内容,请看 初次使用 git 的“核弹级选项”:filter-branch 从仓库中删除文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
git filter-branch --env-filter '
    OLD_EMAIL="rise.worlds@outlook.com"
    NEW_NAME="rise"
    NEW_EMAIL="rise.worlds@live.com"
    if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
    then
        export GIT_COMMITTER_NAME="$NEW_NAME"
        export GIT_COMMITTER_EMAIL="$NEW_EMAIL"
    fi

    if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
    then
        export GIT_AUTHOR_NAME="$NEW_NAME"
        export GIT_AUTHOR_EMAIL="$NEW_EMAIL"
    fi
' --tag-name-filter cat -- --branches --tags

# 覆盖到远程仓库
# git gc
# git push --force --tags origin 'refs/heads/*'

如果要针对个别的仓库这样,要在完成后在仓库中设置新的名字和邮箱

1
2
git config user.name 'rise'
git config user.email 'rise.worlds@live.com'

-—————– 2025-12-31更新:现在可以使用 git-filter-repo 来操作,更方便。

1
2
3
4
# 替换所有提交中的"Zhang San"为"Rise"
git-filter-repo --name-callback 'return name.replace(b"Zhang San", b"Rise")' --force
# 替换所有提交中的"rise.worlds@outlook.com"为"rise.worlds@live.com"
git-filter-repo --email-callback 'return email.replace(b"rise.worlds@outlook.com", b"rise.worlds@live.com")' --force

注意: 使用git-filter-repo后要重新关联远程仓库

1
git remote add origin <your-remote-repo-url>