前言

作為一個稱職的 programmer
當然總會試過輸入錯誤的 git commit message😎
一般的 IDE 也不會提供修改的功能
但這也不代表做不到
讓我們一起來看看
要怎樣用 git command 做到吧

不過要注意的是
改動 Git 的記錄是很危險的動作
可能會導致記錄丟失
或是版本衝突
請確保沒有其他人在跟你同時操作這個 repository 才進行以下操作

同時也建議 clone 一個 branch 出來先試操作一次
然後再在你要修改的 branch 上修改


修改上一個 commit message

如果你輸入錯的是上一個 commit 的 message
那麼要修改也是非常簡單的
只要輸入下面這句即可

git commit --amend -m "<your new commit message>"

e.g.

git commit --amend -m "New commit message"

然後用下面這句強行覆蓋 origin 的記錄

git push --force

這樣就完成啦


修改之前的 commit messages

如果你想修改的不是上一個 commit message
那麼在操作上就會有一點麻煩了

你可以先用下面這句顯示最近 N 次的 commit messages

git rebase -i HEAD~<number>

e.g. 要顯示最近 8次的 commit messages

git rebase -i HEAD~8

 

然後你就應該會看到類似這樣的檔案輸出

pick a1d985b Old message 1
pick 185afe1 Old message 2
pick b1ab811 Old message 3
pick 543378a Old message 4

<...省略...>

# Rebase xxxxxxx..xxxxxxx onto xxxxxxx (10 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup [-C | -c] <commit> = like "squash" but keep only the previous
#                    commit's log message, unless -C is used, in which case
#                    keep only this commit's message; -c is same as -C but

<...以下省略...>

這個檔案應該是用 vim 打開的
如果不是 vim 的話請自行解決 ((笑

你可以看到下面有一大段的 comment
comment 就是在提示你可以怎樣使用 git rebase

這次我們要用到的就是 reword

我們先輸入 i
然後把想要更改的 commit message 前的 pick 換成 reword
就像是這樣

pick a1d985b Old message 1
reword 185afe1 Old message 2
pick b1ab811 Old message 3
reword 543378a Old message 4

<...省略...>

# Rebase xxxxxxx..xxxxxxx onto xxxxxxx (10 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup [-C | -c] <commit> = like "squash" but keep only the previous
#                    commit's log message, unless -C is used, in which case
#                    keep only this commit's message; -c is same as -C but

<...以下省略...>

然後輸入 :wq 作保存
保存後會打開類似下面的檔案來修改

Old message 2

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.

<...以下省略...>

同樣的按 i 開始修改
修改後按 :wq 保存即可

重覆上面的步驟直至所有需要修改的記錄都修改完畢

 

保存後用下面這句強行覆蓋 origin 的記錄

git push --force


恭喜你完成修改了啦🥳


參考資料

https://stackoverflow.com/questions/179123/how-to-modify-existing-unpushed-commit-messages


廣告欄位
本站致力於為大家提供乾淨舒服的獲取資訊途徑
並盡量把廣告對閱讀體驗的影響降至最低
若想支持本站營運
可點擊此處打開廣告
廣告的內容並非由本站控制
請小心驗證廣告內容
感謝各位看客的支持 ( •̀ ω •́ )y


在〈[碰壁指南] 輸入了錯誤 commit message?Git rebase 修改沒煩惱〉中有 1 則留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *


Trending