Git使いになろう:ひとりで使う(6:一つ前のコミットまでHEADの参照のみを戻す)

さて、

1
$ git reset --hard HEAD^

では、ワーキングツリー、インデックス共に一つ前のコミットに戻りましたが、
commitだけを戻す場合は

1
$ git reset --soft HEAD^

を使います。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ git status
On branch master
nothing to commit, working directory clean
$ git --no-pager log
commit ee8831f07fcd5007816ef6e75682b826659a79cd
Author: tomohiro <tomohiro@example.com>
Date:   Fri Jan 1 20:51:25 2016 +0900
 
    add URL
     
    add the URL of the Ragtimeblues
 
commit ab374c5f64e3de33b079b9e013ac2cec7830935d
Author: tomohiro <tomohiro@example.com>
Date:   Fri Jan 1 16:57:09 2016 +0900
 
    first commit

という状態で、

1
$ git reset --soft HEAD^

を実行してみると、

1
2
3
4
5
6
7
8
9
10
11
12
13
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
 
    modified:   sample.txt
 
tomohiro@imola:~/sandbox.test$ git --no-pager log
commit ab374c5f64e3de33b079b9e013ac2cec7830935d
Author: tomohiro <tomohiro@example.com>
Date:   Fri Jan 1 16:57:09 2016 +0900
 
    first commit

となり、コミットのみが一つ前に戻せます。

Git使いになろう:ひとりで使う(5:一つ前のコミットまでワーキングツリー、インデックス共に戻す)

コミットした後で「やっぱりこのcommitはなかったことにしたい」というときは、

1
$ git reset --hard HEAD^

を使います。

今、Gitのログが

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ git --no-pager log
commit ee8831f07fcd5007816ef6e75682b826659a79cd
Author: tomohiro <tomohiro@example.com>
Date:   Fri Jan 1 20:51:25 2016 +0900
 
    add URL
     
    add the URL of the Ragtimeblues
 
commit ab374c5f64e3de33b079b9e013ac2cec7830935d
Author: tomohiro <tomohiro@example.com>
Date:   Fri Jan 1 16:57:09 2016 +0900
 
    first commit

となっているとき、一つ前に戻してみます。

1
2
$ git reset --hard HEAD^
HEAD is now at ab374c5 first commit

これで、OKです。再度ログを確認してみると

1
2
3
4
5
6
$ git --no-pager log
commit ab374c5f64e3de33b079b9e013ac2cec7830935d
Author: tomohiro <tomohiro@example.com>
Date:   Fri Jan 1 16:57:09 2016 +0900
 
    first commit

となっており、sample.txtの内容も

1
2
$ cat sample.txt
Ragtimeblues

と、最初のコミット内容に戻っています。

Git使いになろう:ひとりで使う(4:編集中のファイルを元に戻す)

ファイルを編集中にやっぱり「やーめた」となって、元に戻したいときに最新のコミット状態にしてみます。

~/sandbox/sample.txt の内容を

1
2
3
Ragtimeblues
https://ragtimeblues.net/
sample.txt

に変えました(最後の行を追加)。

状態を確認します。

1
2
3
4
5
6
7
8
9
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
 
    modified:   sample.txt
 
no changes added to commit (use "git add" and/or "git commit -a")

となって、sample.txtが変更されていることがわかります。
この編集を破棄して、最新のコミット状態に戻すにはgit checkoutを使います。

1
$ git checkout HEAD sample.txt

sample.txtの中身を確認すると、

1
2
3
$ cat sample.txt
Ragtimeblues
https://ragtimeblues.net/

となって、元に戻っています。状態を確認すると、

1
2
3
$ git status
On branch master
nothing to commit, working directory clean

で、何も変更がなくきれいであることがわかります。