🌊

[Git] rebase完了後にrebase前の状態に戻す方法

2024/03/04に公開

手順

  1. バージョン履歴の確認
  2. バージョンを任意の状態まで戻す

バージョン履歴の確認

以下のコマンドを実行します。

git reflog

このコマンドを実行すると以下のようなログが出力されます。

4f9aeb8 (HEAD -> feature/reflog-sample1) HEAD@{0}: rebase (finish): returning to refs/heads/feature/reflog-sample1
4f9aeb8 (HEAD -> feature/reflog-sample1) HEAD@{1}: rebase (pick): reflogの確認
d3e47c7 (origin/feature/reflog-sample-2, feature/reflog-sample-2) HEAD@{2}: rebase (start): checkout feature/reflog-sample-2    
a3c08b5 (origin/feature/reflog-sample1) HEAD@{3}: reset: moving to HEAD
a3c08b5 (origin/feature/reflog-sample1) HEAD@{4}: checkout: moving from feature/reflog-sample-3 to feature/reflog-sample1    
8ae4922 (origin/feature/reflog-sample-3, feature/reflog-sample-3) HEAD@{5}: checkout: moving from feature/reflog-sample-2 to feature/reflog-sample-4
d3e47c7 (origin/feature/reflog-sample-2, feature/reflog-sample-2) HEAD@{6}: pull: Fast-forward
65c72bd HEAD@{7}: checkout: moving from feature/reflog-sample1 to feature/reflog-sample-2
a3c08b5 (origin/feature/reflog-sample1) HEAD@{8}: reset: moving to HEAD
a3c08b5 (origin/feature/reflog-sample1) HEAD@{9}: commit: reflogを試してみる
65c72bd HEAD@{10}: checkout: moving from feature/reflog-sample-2 to feature/reflog-sample1
65c72bd HEAD@{11}: checkout: moving from develop to feature/reflog-sample-2
8f0fdf1 (develop) HEAD@{12}: clone: from https://github.com/reflog-test

バージョンを任意の状態まで戻す

先ほど実行したgit reflogの出力結果から、自身が戻りたバージョンを確認します。
まず、実際に戻りたいバージョン履歴を指定する方法を確認します。
任意のバージョンを指定する方法はHEAD@{n}です。

今回はa3c08b5 (origin/feature/reflog-sample1) HEAD@{4}: checkout: moving from feature/reflog-sample-3 to feature/reflog-sample1 に戻すことを想定することとします。
そのため、指定するバージョンはHEAD@{4}とすることで目的のバージョンを指定することが可能です。
次にバージョンを戻すためのコマンドを確認します。
今回使用するコマンドはgit reset --hard HEAD{n}です。
実際に、戻りたいバージョンを指定し、以下のコマンドを実行します。

git reset --hard HEAD@{4}

これで指定したバージョン、今回はrebaseを実行する1つ前の状態まで戻ることができます。

参考記事

Discussion