git reset(git add/commitの取り消し)

前提知識

ワーキングツリー
現在の状態
インデックス
ワーキングツリーからgit addした状態
HEAD
最後にコミットした状態
HEAD^
HEADの1つ前のコミットした状態

git resetとは?

ワーキングツリーやインデックスやHEADの位置を移動する。(なお、コミットを修正する場合はgit commit --amendを使う。)

git resetのオプションとその機能

soft

 git reset --soft HEAD^

HEADの位置をHEAD^へ変更する。インデックスとワーキングツリーに影響はない。

mixed(またはオプションなし)

 git reset --mixed HEAD
 git reset HEAD

HEADの位置とインデックスをHEADへ変更する。ワーキングツリーに影響はない。

hard

 git reset --hard HEAD^

HEADの位置とインデックスとワーキングツリーをHEAD^へ変更する。

使用例

修正したファイルを元のファイルに戻す

 vi test.txt               # (1) test.txtを修正する。
 git checkout test.txt     # (2) (1)の修正を戻す。

修正したワーキングツリーを元の状態(HEAD)のワーキングツリーに戻す

 vi test1.txt              # (1) test1.txt,test2.txtを修正する。
 vi test2,txt
 git reset --hard HEAD     # (2) (1)の修正を戻す。

ステージングを取り消す

 vi test.txt               # (1) test.txtを修正する。
 git add test.txt          # (2) test.txtをステージングする。
 git reset HEAD test.txt   # (3) 上のステージングを取り消す。
                           #     test.txtは修正されたまま。

コミットログを書き直したい/必要な修正ファイルをaddしてなかった(不要な修正ファイルをaddしてた)

 vi test.txt               # (1) test.txtを修正する。
 git add test.txt          # (2) test.txtをステージングする。
 git commit -am 'fixed'    # (3) コミットする。
 git reset --soft HEAD^    # (4) 上のコミットを取り消す。
 vi test2.txt              # (5) test2.txtを修正する。
 git add test2.txt         # (6) test2.txtをステージングする。
 git commit -am 'fixed 2 files' # (7) コミットし直す。
                                #     test.txt、test2,txt共に修正がコミットされた。
 

(コミットしてすぐの場合の)コミットを取り消す

 vi test.txt               # (1) test.txtを修正する。
 git add test.txt          # (2) test.txtをステージングする。
 git commit -am 'fixed'    # (3) コミットする。     
 git reset --hard HEAD^    # (4) 上のコミットを取り消す。
                           #     コミットログ'fixed'は消え、test.txtは修正前の状態に戻っている。

(コミットして時間が経っていて、すでに他者が修正を行っている可能性が高い場合の)コミットを取り消す

 自分:
 git commit -am 'XXX'
 git push
 他者:
 git pull
 git commit -am 'XXX'
 自分:
 git revert HEAD
 git push
 (他者)
 git pull

git resetしたが、さっき取り消したコミットの内容を見たい

 git reset --soft HEAD^
 git show ORIG_HEAD

他にも

 vi test.txt                 # (1) test.txtを修正する。
 git add test.txt            # (2) これをステージングして、
 git commit -am 'fixed'      # (3) コミットする。
 git reset --hard HEAD^      # (4) このコミットを取り消す。
 vi test.txt                 # (5) 再度、test.txtを修正する。
 git diff ORIG_HEAD test.txt # (6) (1)の修正とのdiffを見る。

間違ってgit resetしてしまったので、元に戻したい

Git/git reflog (git resetを取り消す)を参照。

参考


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS