Git で 変更を一時的によける
あるブランチで色々変更をしていて、中途半端だけど、急遽他のブランチで作業をしなければならなくなった時に、 git stash
というコマンドが便利です。
変更を加える
➜ sample git:(hoge) touch hoge.txt ➜ sample git:(hoge) ✗ git add . ➜ sample git:(hoge) ✗ git commit -m "hoge.txt の作成" ➜ sample git:(hoge) hoge.txt の編集 ➜ sample git:(hoge) ✗ git status On branch hoge 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: hoge.txt no changes added to commit (use "git add" and/or "git commit -a")
hoge.txt が作成されている hoge ブランチで hoge.txt を編集します。
git status
でワークツリーに変更が加わっていることが確認できています。
変更をよける
ここで git stash
を実行して、変更を一時的によけてみます。
➜ sample git:(hoge) ✗ git stash Saved working directory and index state WIP on hoge: 2e894e0 hoge.txt の作成 HEAD is now at 2e894e0 hoge.txt の作成 ➜ sample git:(hoge) git status On branch hoge nothing to commit, working directory clean
すると、git status
を実行しても先ほどの hoge.txt の変更は表示されません。
一時的によけた変更は、 git stash show
で確認できます。
➜ sample git:(hoge) git stash show hoge.txt | 1 + 1 file changed, 1 insertion(+)
他のブランチで変更を加える
そして、fuga ブランチへ checkout して fuga.txt を作成し、これをコミットします。
➜ sample git:(hoge) git checkout fuga Switched to branch 'fuga' ➜ sample git:(fuga) touch fuga.txt ➜ sample git:(fuga) ✗ git add . ➜ sample git:(fuga) ✗ git commit -m "fuga.txt の作成" [fuga 199f6b5] fuga.txt の作成 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 fuga.txt
git show
でコミット内容を確認してみても、hoge ブランチで行った作業の内容はコミットされていないことが確認できます。
➜ sample git:(fuga) git show commit 199f6b526fc2b6612e31b8e913df2fe2ae4f0d42 Author: fuga <fuga@fuga.fuga> Date: Mon May 23 23:11:46 2016 +0900 fuga.txt の作成 diff --git a/fuga.txt b/fuga.txt new file mode 100644 index 0000000..e69de29
変更を戻す
次に、再び hoge ブランチへ checkout します。
先ほど一時的によけた変更を元に戻すには git stash pop を実行します。
➜ sample git:(fuga) git checkout hoge Switched to branch 'hoge' ➜ sample git:(hoge) git stash pop On branch hoge 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: hoge.txt no changes added to commit (use "git add" and/or "git commit -a") Dropped refs/stash@{0} (8e370d4ff891b72ee304fca8bca60b7371663fff)
念のため git status を実行してみると、変更が元に戻っていることが確認できます。
➜ sample git:(hoge) ✗ git status On branch hoge 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: hoge.txt no changes added to commit (use "git add" and/or "git commit -a")