Daiブログ

普段学習したことや生活のことについて書いていきます〜

プッシュしてしまったコミットメッセージを変更する

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 5comment 4に変更します。 コミットメッセージを編集する場合pickeditに変えてあげます。

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

これでリモートの方もコミットメッセージを変更することができました!