カイワレの大冒険 Third

技術的なことや他愛もないことをたまに書いてます

過去に戻れ!reflogを使いこなしてこそGit中級者である。

Gitの一番好きなコマンドといっても過言ではない reflog 。 すごく便利なので、使いましょうと言う話です。

簡単にいえば、 reflog で過去を探索し、 reset で好きなタイミングに戻ることができるというテクニックです。

開発していると、ここまでいじっちゃったけど、ここまで戻したいとかそういう欲が出てきます。 そういうときに是非使って欲しいコマンドです。

では説明していきます。

まず説明用に、いくつかファイルを作り、コミットなり色々しときます。

$ cd ~/work/
$ mkdir git
$ cd git/

$ git init
Initialized empty Git repository in /Users/masudak/work/git/.git/

# 適当にファイルを作る
$ touch sample.txt
$ git status
On branch master

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    sample.txt

$ git add sample.txt

$ git commit
[master (root-commit) 4544b55] initial commit
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 sample.txt

$ ls
sample.txt

# ブランチきる
$ git checkout -b hotfix-sample
Switched to a new branch 'hotfix-sample'

# また適当にファイルを作る
$ touch sample2.txt

$ git add sample2.txt


$ git commit
[hotfix-sample 3d7c0f6] sample
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 sample2.txt

$ ls
sample.txt  sample2.txt

ここで reflog !! こんな感じで、履歴を見ることができます。大事なのは一番左の列の文字の羅列(ハッシュ)。

$ git reflog
3d7c0f6 HEAD@{0}: commit: sample
4544b55 HEAD@{1}: checkout: moving from master to hotfix-sample
4544b55 HEAD@{2}: commit (initial): initial commit

4544b55 に戻ってみましょう!

$ git reset --hard 4544b55
HEAD is now at 4544b55 initial commit

戻れたかみてみる。

$ git log -1
commit 4544b551e874d864a55de13ced8d5f8ce4045795
Author: masudak <masuda@sample.com>
Date:   Thu Jun 23 19:52:35 2016 +0900

    initial commit


$ ls
sample.txt

戻れたー。

終わりに

非常に便利ですので、覚えておくとかなり移動が楽になります。 是非是非使ってみてください!ではでは!

こちらもどうぞ。

blog.masudak.net

blog.masudak.net