LoginSignup
7
4

More than 5 years have passed since last update.

誤ってGitのブランチを消してしまった場合の戻し方

Posted at

ローカルとリモート両方のブランチを消してしまった場合の戻し方です。
SourceTreeを使用しています。

コミット

状況を再現するためmasterブランチを作りコミットをします。
その後masterからdevelopブランチを作り2つコミットします。
スクリーンショット 2016-10-31 20.23.33.png

この状態からdevelopブランチを削除します。
スクリーンショット 2016-10-31 20.23.52.png

コミットの戻し方(新しいブランチ作成)

ローカルにもリモートにもブランチが無いため、Gitのコマンドにて戻してみます。
git reflog を行う事でコミットのログを見る事が出来ます。

$ git reflog
b2a9d16 HEAD@{0}: checkout: moving from develop to master
a5778af HEAD@{1}: checkout: moving from master to develop
b2a9d16 HEAD@{2}: checkout: moving from develop to master
a5778af HEAD@{3}: commit: test3
9281d3c HEAD@{4}: commit: test2
b2a9d16 HEAD@{5}: checkout: moving from master to develop
b2a9d16 HEAD@{6}: commit (initial): test1

この中から戻りたいコミットのIDと新しいブランチ名を指定する事で戻れます。
git branch 新しいブランチ名 コミットID

$ git branch develop a5778af

スクリーンショット 2016-10-31 20.25.06.png

新しくdevelopブランチが作成されtest3のコミットに戻れました。

コミットの戻し方(現在のブランチを使用)

同じようにgit reflogのコミットにgit reset コミットIDで現在のブランチで指定コミットに戻る事も出来ます。

$ git reflog
b2a9d16 HEAD@{0}: checkout: moving from develop to master
a5778af HEAD@{1}: checkout: moving from master to develop
b2a9d16 HEAD@{2}: checkout: moving from develop to master
a5778af HEAD@{3}: commit: test3
9281d3c HEAD@{4}: commit: test2
b2a9d16 HEAD@{5}: checkout: moving from master to develop
b2a9d16 HEAD@{6}: commit (initial): test1

$ git reset a5778af

スクリーンショット 2016-10-31 20.26.41.png

現在のブランチ(今回はmaster)のまま、test3のコミットに戻れました。

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4