rebase -i コマンドについて

git rebase -i コマンドが色々と便利なのでまとめてみました。

注: pushしたコミットに対して使用しないでください。

対話モードに入る

git rebase -i <コミットid>

# 例
git rebase -i HEAD~2

すると、下記のようなテキストエディタが開きます。
pickという箇所を書き換える事で、様々な作業を行うことができます。

# 指定したコミットを基点に上から古い順番に並びます。
pick 326fc9f addの説明を追加
pick 9a54fd4 commitの説明を追加
pick 0d4a808 pullの説明を追加

# Rebase 326fc9f..0d4a808 onto d286baa
#
# 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
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#

コミットメッセージのみを修正する

変更したいコミットのpickをrかrewordに変更します。

# 変更前
pick 326fc9f addの説明を追加

# 変更後
r 326fc9f addの説明を追加

テキストエディタを終了すると、そのままコミットエディタが開くのでコミットメッセージを修正します。

コミットを編集する

変更したいコミットのpickをeかeditに変更します。

# 変更前
pick 9a54fd4 commitの説明を追加

# 変更後
e 9a54fd4 commitの説明を追加

テキストエディタを終了すると、下記のように表示されます。

Stopped at 2143060...  commitの説明を追加
You can amend the commit now, with

  git commit --amend 

Once you are satisfied with your changes, run

  git rebase --continue

基本的には以下の流れで行います。
1. ファイルを修正する。
2. git add コマンドでステージに追加する。
3. git commit --amend コマンドでコミットを修正する。
4. git rebase --continueで完了する。

注:
git rebase --continueを行って、他のコミットとコンフリクトが発生した場合は
その箇所を修正します。修正後、git addを行い、再度 git rebase --continueを
実行してください。

コミットの順番を並び替える

対話モード内でコミットの順番を変更するだけでokです。

# 変更前
pick 326fc9f A
pick 9a54fd4 B
pick 0d4a808 C

# 変更後
pick 9a54fd4 B
pick 326fc9f A
pick 0d4a808 C

コミットを削除する

対話モード内で適当な行を削除するか、pickをdかdropに変更します。

# 変更前
pick 326fc9f A
pick 9a54fd4 B
pick 0d4a808 C

# 変更後
pick 9a54fd4 B
# pick 326fc9f A # <= コメントアウトでも可
d 0d4a808 C

コミットを一つにまとめる

pickをsかsquashに変更します。squashを指定したコミットは直前のコミットと一つになります。

# 変更前
pick 326fc9f A
pick 9a54fd4 B
pick 0d4a808 C

# 変更後
pick 326fc9f A
s 9a54fd4 B
pick 0d4a808 C

対話モードを終了後、コミットエディタが開くのでコミットメッセージを編集して終了してください。

途中で編集を中止する

git rebase --abort