プッシュしてしまったコミットメッセージを変更する
gitを使っていく中でコミットメッセージの変更をすることがあったのでやり方をこちらにメモしておこうと思いました。 これから行うのはすでにリモートにプッシュしてしまったコミットのメッセージの変更です!
- git rebase -i HEAD~n 上記のコマンドを実行することでHEADからn個までのコミットを表示できる
$git rebase -i HEAD~4 pick 3ba3a2e commit comment 1 pick 6ef356e commit comment 2 pick d84a911 commit comment 3 pick 9a34966 commit comment 5
今回はcomment 5
をcomment 4
に変更します。
コミットメッセージを編集する場合pick
をedit
に変えてあげます。
pick 3ba3a2e commit comment 1 pick 6ef356e commit comment 2 pick d84a911 commit comment 3 edit 9a34966 commit comment 5
編集が終わったら:wq
で保存終了します。
そうすると以下のような表示が出ると思います。
$ git rebase -i HEAD~4 Stopped at 9a34966... comment 5 You can amend the commit now, with git commit --amend Once you are satisfied with your changes, run git rebase --continue
- コミットメッセージの編集 以下のコマンドでメッセージの編集を行っていきます。
$git commit --amend
コマンドを実行すると以下のような表示が出ると思います。
comment 5 # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. #以下省略
メッセージを編集します。今回はcomment 4
に変更。
comment 4 # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. #以下省略
編集が終わったら:wq
で保存終了。
以下のような画面が出ればokです!
$ git commit --amend [detached HEAD ] comment 4追加 Date: Wen Dce 20 19:11:02 2020 +0900 1 file changed, 1 insertion(+) create mode 100644 comment 4
以下のコマンドでrebaseを実行し終了。
$git rebase --continue
- リモートリポジトリにプッシュする
変更した結果をリモートへプッシュします。
プッシュする場合は
git push -f
ではなくgit push --force-with-lease
を使いましょう!git push --force-with-lease
はローカルとリモートを比較し、ローカルが最新ならプッシュに成功します。 複数人でプロジェクトを進めている場合、git push -f
してしまうとリモートが最新なのにその変更を打ち消してしまう恐れがあります。
$git push --force-with-lease origin master
これでリモートの方もコミットメッセージを変更することができました!