如何回退到倒數第二個 Commit 並刪除遠端最後一次提交
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1123
在日常開發中,我們有時會遇到這樣的情境:
「我剛剛 push 了一個錯誤的 commit,上線前發現問題了,想要把它從本地和遠端都徹底刪除!」
這篇文章將介紹如何透過 Git 指令,回退到倒數第二個 commit 並刪除遠端最後一次提交。
🎯 目標
-
本地移除最新一筆提交(commit)
-
同步遠端狀態,讓遠端也刪除這筆提交
🧩 指令操作步驟
1️⃣ 回退本地 commit:git reset --hard HEAD~1
git reset --hard HEAD~1
這條指令會將本地分支回退一個版本,刪除最近的 commit,並將工作目錄一併回復(即代碼也會回到前一版本)。
如果你只是想取消 commit,但保留代碼變動,請改用:
git reset --soft HEAD~1
2️⃣ 強制推送到遠端:git push --force
git push origin main --force
這會把你目前的 HEAD 狀態強制推送到遠端,覆蓋掉遠端的最新 commit。
⛳️ 請注意:如果你的分支不是
main
,請替換為實際分支名稱,例如:git push origin dev --force
⚠️ 注意事項
-
這會改寫 Git 歷史,若其他人也有 pull 過那個 commit,他們的本地分支會和遠端衝突。
-
強烈建議在多人協作環境下,和團隊確認後再執行
--force
推送。 -
若已經發佈至生產環境,請評估是否需要 rollback 或 hotfix,而不是直接改 Git 歷史。
✅ 小結
操作 | 指令 |
---|---|
回退本地一筆提交 | git reset --hard HEAD~1 |
強制同步遠端 | git push origin main --force |
若想保留變更內容 | git reset --soft HEAD~1 (取消提交但保留改動) |
透過這些指令,可以讓我們在必要時「回到過去」,糾正錯誤的提交歷史,保持專案的乾淨與正確。
This article was last edited at