修改上一個 Git 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/1139
有時候我們在 Git 中提交了一個 commit 之後,才發現小地方有個缺漏,或想將一個修改合併轉成紅線內部的 commit,這時就可以用下列三個 Git 命令來達到效果:
git add .
git commit --amend --no-edit
git push -f
各指令介紹
1. git add .
將所有變更加入到 Git 的穩定區 (staging area),等待提交
2. git commit --amend --no-edit
將 staging 區的變更「合併進上一個 commit 中」,而不修改 commit 說明
-
--amend
:重新撰寫上一個 commit -
--no-edit
:保留原本的 commit message
這個指令很適合我們想 "補上一個 commit 內容,但不重新開一個 commit"。
3. git push -f
強制 push 到遠端,變更 commit 歷史
-
--force
(簡字是-f
),是因為--amend
使得 commit hash 改了,需要重新更新遠端
如果是自己分支,這樣 push -f 是完全正常的
結論
這套指令給你的是:
-
保留簡潔的 commit 歷史
-
不需添加新 commit
-
補上前次未進 staging 的缺漏
是 Git 單人分支或流程經濟本地編變時常用的必備技巧。
→返回目錄:GitBash使用手冊
This article was last edited at 2025-04-25 01:42:29