git commit --amend 二つ以上前のcommit の編集方法、丁寧に解説

fugaのcommit messageを編集したい。

$ g log --oneline
068bc0b bar
19b06a6 fuga
6f04c12 hoge

rebaseする。

$ git rebase -i HEAD~3

vimが開くので、該当コミットをpickからeに変えて保存(:wq)

pick 6f04c12 hoge
- pick 19b06a6 fuga
+ e 19b06a6 fuga
pick 068bc0b bar

# Rebase 51268e2..068bc0b onto 51268e2 (3 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
etc

そうするとvimが閉じてこれが出る

Stopped at 19b06a6... fuga
You can amend the commit now, with

        git commit --amend 

Once you are satisfied with your changes, run

        git rebase --continue

rebaseすると終わってしまうので、git commit –amend をする。

$ g commit --amend

またvimが開くので変えたい箇所を編集

+ changed fuga
- fuga

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Wed Aug 2 08:17:54 2017 +0900
#
# interactive rebase in progress; onto 51268e2
# Last commands done (2 commands done):
#    pick 6f04c12 hoge
#    e 19b06a6 fuga
# Next command to do (1 remaining command):
#    pick 068bc0b bar
etc

確認するとHEADはchanged fugaになっている

$ g log --oneline
275e529 changed fuga
6f04c12 hoge

最後に忘れずにrebase continue

$ g rebase --continue
Successfully rebased and updated refs/heads/master.

やったー、編集できた!!

$ g log --oneline
e0feff0 bar
275e529 changed fuga
6f04c12 hoge

まとめ

$ git rebase -i HEAD~3
$ g commit --amend
$ g rebase --continue

Reference from

Git ふたつ以上前のコミットには commit --amend できないの? - Qiita git rewrite history - How to modify a specified commit in git? - Stack Overflow