# git rebase 合併 commit 和 修正 commit msg **暫時性的把 code 丟到遠端分支上、Commit 到遠端分支後才發現原來還有小錯誤要改?!** 有時會遇到丟上遠端 git 後發現還有部分需要修改, 如果再丟了一個 commit 上去, 容易讓 code reviewer 感到混亂, 此時的 commit message 也難以定義這兩個 commit 的差異, 或是變成多了一個 bugfix 的 commit, 但實際上只是前一個 commit 的修訂。 好的架構是要維護清楚 git commit message/history, 每一次都好好整理才不會累積 technical debt, 此時我們可以用 git rebase 來整理 commit ## 先確認 commit id ``` o@W11GHYLPN3:~/work/test-repo$ git log --oneline 860483b (HEAD -> master, origin/master) temp dbf06eb trivial: dev setup script f1fbdd8 trivial: init readme ``` 以上述為例, 我們要把上述的 temp commit (860483b) 合併到 trivial commit (dbf06eb) ## git rebase and squash commit (要用前一個 commit: f1fbdd8) ``` o@W11GHYLPN3:~/work/test-repo$ git rebase -i f1fbdd8 ``` ``` GNU nano 6.2 pick dbf06eb trivial: dev setup script pick 860483b temp ``` 會出現以上訊息, 把我們暫時性放上去的 commit, 改成 squash, 儲存送出 ``` GNU nano 6.2 pick dbf06eb trivial: dev setup script squash 860483b temp ``` 接著會出現修改 commit message 的對話框, 修改後儲存送出 ``` GNU nano 6.2 /home/rileykao/work/test-repo/.git/COMMIT_EDITMSG # This is a combination of 2 commits. # This is the 1st commit message: trivial: dev setup script # This is the commit message #2: temp ``` ## git push -f 到遠端 ``` o@W11GHYLPN3:~/work/test-repo$ git push origin master -f ``` 就成功整理 commit 囉! ``` o@W11GHYLPN3:~/work/test-repo$ git log --oneline 2a5d1d5 (HEAD -> master, origin/master) trivial: dev setup script f1fbdd8 trivial: init readme ```