この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
現在の作業ツリーを保存する
前回はブランチのマージについて解説しました。今回は現在の作業ツリーを一時的に保存する、git stashコマンドについて説明します。
git stashコマンドは、現在の作業ツリーの状態を一時的に保存するためのコマンドです。 いまの状態をコミットせず、ちょっとほかのブランチに対して作業を行いたい場合などに使用します。 まずはmasterブランチを選択し(git checkout master)、ファイルをなにか変更して保存しましょう。 そのままaddせず、git stashコマンドを実施します。
$ git stash save "一時保存"
Saved working directory and index state On master: 一時保存
git stashを実施すると、その時点での作業ツリーが一時保存され、作業ツリーはHEADの状態に戻ります。 また、git stash save <コメント>とすれば、コメントを付加できます。 では、現在stash領域に保存されているリストを確認してみます。
$ git stash list
stash@{0}: On master: 一時保存
現在、「stash@{0}」という名前のstashがあるのが確認できます。ではこのstashを復元しましょう。
$ git stash apply stash@{0}
# 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: hello.html
#
no changes added to commit (use "git add" and/or "git commit -a")
これでさきほどの作業ツリーが復元できました。
ここでもう一度git stash listで確認してみます。
$ git stash list
stash@{0}: On master: 一時保存
stash領域はそのまま残っています。では、今度は別の方法で復元してみましょう。 もう一度stash saveでstash領域に保存します。
$ git stash save "もう一度一時保存"
Saved working directory and index state On master: もう一度一時保存
HEAD is now at 9b343c2 Merge branch 'merge_test'
これでstashは2つになりました。git stash listを実行すると、2つになっているのがわかります。では復元してみましょう。
$ git stash pop
# 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: hello.html
#
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (4250a92648f08e7c91998d5d75b567040c1d5b31)
$ git stash list
stash@{0}: On master: 一時保存
今度は、git stash popとしました。popで復元すると、復元したstash領域は削除されます。 stashを残したいときはapply、削除してもいいときはpopを使用しましょう。
それ以外にもいくつかstash関連のコマンドがあります。 git stash showコマンドを実行すると、いまの作業ツリーとstashの作業ツリーの差分を表示できます。
$ git stash show
hello.html | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)
git stash dropを使用すれば、指定したstashを削除できます。
$ git stash list
stash@{0}: WIP on master: 9b343c2 Merge branch 'merge_test'
$ git stash drop stash@{0}
Dropped stash@{0} (e041b13d2c5a7a8b0cb49072dfd8cf1a9a495067)
また、git stash clearを実行すれば、すべてのstashが削除されます。
最後に、stashからブランチの作成をしてみましょう。
$ git stash branch stash_brahch stash@{0}
Switched to a new branch 'stash_brahch'
# On branch stash_brahch
# 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: hello.html
#
no changes added to commit (use "git add" and/or "git commit -a")
Dropped stash@{0} (9776ba4d56e8c742af557fa22e008683f99ddb27)
$ git branch
master
merge_test
* stash_brahchgit stash branch new-branch stash@{1}
git stash branch <ブランチ名>
今回は作業ツリーの保存・復元を行うstashについて解説しました。 次回はgitの履歴操作について解説する予定です。