在 Git 中,已提交的 commit 的 名稱(Name)
和 電子郵件(Email)
是可以變更的,但這會改變 commit 的歷史記錄,因此需要重新提交並強制推送。
變更某次提交的 Email 和名稱的方法
1. 如果是最後一次提交
如果你只是想變更最近的一次提交,可以使用:
git commit --amend --author="新名稱 <新Email>"
這將修改最新的一次 commit,然後你需要強制推送(如果已經推送到遠端):
git push --force
2. 變更特定 commit 的 Email 和名稱
如果是某個舊的 commit,你需要使用 git rebase
來變更。
步驟
找出要修改的 commit:
git log --pretty=format:'%h %an <%ae>' --reverse
這會顯示 commit ID、名稱與 Email,找到需要變更的 commit ID。
進行交互式 rebase:
git rebase -i <要變更的 commit 的上一個 commit ID>
例如,如果要修改 abc1234
,你應該執行:
git rebase -i abc1234^
進入編輯模式後,把 pick
改成 edit
,然後存檔退出。
修改該 commit 的名稱和 Email:
git commit --amend --author="新名稱 <新Email>"
讓 rebase 繼續:
git rebase --continue
如果這些 commit 已經推送到遠端,則需要強制推送:
git push --force
3. 批次修改整個倉庫的 Email
如果你想一次修改所有 commit(例如你的 Git 設定錯誤),可以使用 git filter-repo
或 git filter-branch
來批次修改。
使用 git filter-repo
(推薦,較新):
git filter-repo --commit-callback '
if commit.author_email == b"舊的Email":
commit.author_email = b"新的Email"
commit.author_name = b"新名稱"
if commit.committer_email == b"舊的Email":
commit.committer_email = b"新的Email"
commit.committer_name = b"新名稱"
'
然後強制推送:
git push --force --all
注意事項
- 影響歷史紀錄:這會改變 commit 的 SHA 值,因此會影響其他已拉取該 commit 的協作者。如果多人協作,最好先確認影響範圍再執行。
- 需要強制推送(force push):如果 commit 已經推送到遠端,就需要
git push --force
,這可能會覆蓋遠端歷史。
- 避免在公共倉庫修改已推送的歷史:如果多人共用該 repo,請小心,因為強制推送會讓其他人的歷史產生衝突。
如果這是誤設的 Email,未來可以先透過 git config
設定正確的 Email:
git config --global user.name "你的名稱"
git config --global user.email "你的Email"
這樣新 commit 就不會再出錯了。