LoginSignup
70
42

More than 1 year has passed since last update.

【Git】一時的に過去のcommitに戻りたい

Last updated at Posted at 2021-07-14

はじめに

不具合等が発生した際に、発生個所を突き止めるため一時的に過去のcommitに戻って操作したい場合は無いだろうか?今回は、その方法を以下に記載する(最新のcommit状態に戻す方法も併せて記載する)。

結論

ブランチを過去のcommitに戻す手順と、最新の状態に戻すコマンドを記載する。

■ ブランチを過去のコミットに戻す

$ git checkout <コミット名>

■ 最新の状態に戻す

$ git checkout <ブランチ名>

詳細

■ 操作するブランチを確認

まず初めに、操作するブランチを確認する。
現在のブランチはfeature/testである。

$ git branch 

master
* feature/test

■ 戻りたいcommit名を探す

次に、戻りたいcommit名を探す。
この場合、commit名は以下の通りである。

  • 13gsd8g9skegjaosdjgnaewiura7g
  • ckawijsgs863462wijngoasgeni1a
$ git log

commit 13gsd8g9skegjaosdjgnaewiura7g (HEAD)
Author: name <name@google.com>
Date:   Tue Jul 13 13:00:00 2021 + 0900

commit ckawijsgs863462wijngoasgeni1a
Author: name <name@google.com>
Date:   Tue Jul 13 10:00:00 2021 + 0900

■ 過去のcommitに戻る

次に、戻りたいcommit名を指定してコマンドを実行する。
今回はckawijsgs863462wijngoasgeni1aに戻る。

$ git checkout ckawijsgs863462wijngoasgeni1a

因みに、先頭4文字(今回ならckaw)までなら省略可能である。

$ git checkout ckaw

以上で、過去のcommitに戻ることが出来た。

■ 過去のcommitに戻した状態で現在のブランチを確認する

$git branch 

* (HEAD detached ckawijsg)
master
feature/test

先ほどまで、feature/testが現在操作しているブランチであったが、(HEAD detached ckawijsg)に変わっている。このことから、過去のcommitに戻ると、操作しているブランチとは異なるブランチを一時的に作成していることが分かる。そのため、最新のcommit状態に戻したい場合には、ブランチを変更してあげれば良い。

■ 最新のcommitに戻す

$ git checkout feature/test

これで、過去のcommit状態に戻った後に、再度現在のcommit状態に戻すことが出来た。ちなみに、現在のブランチをfeature/testにすると、(HEAD detached ckawijsg)は消える。

70
42
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
70
42