git stash コマンドを使ってファイルの変更を一時退避
git stash とは
git stash コマンドは、Git における作業フローを柔軟にする強力なツールです。基本的な使い方といくつかの応用例を解説します。
Use
git stashwhen you want to record the current state of the working directory and the index, but want to go back to a clean working directory.
公式ドキュメント (https://git-scm.com/docs/git-stash) より抜粋。
stash の構造について
stash は単なるコミットではない: stash は、通常のコミットとは異なり、インデックスとワークツリーの状態を保存したものです。そのため、未追跡ファイル や インデックスにステージングされていない変更 も保存できます。
stash の構造: stash は、複数の変更をスタック状に保存します。各変更は、
stash@{0}、stash@{1}といったように、stash@{n}という名前で参照できます。
git stash の使い方(基本)
特定のファイルだけを stash :
git stash [push] -- <ファイル名>pushのときはpushを省略可。このコマンドを使うと、指定したファイルを stash に保存し、他のファイルはワークツリーに残すことができます。
- push コマンドでは、stash に保存した変更は一時的に見えなくなります(ファイルの状態が HEAD まで戻る)
まとめて stash :
git stash [push] [--all | --include-untracked | --staged | etc.]—all / -a :
.gitignore等によって無視されているファイルもすべて含む—include-untracked / -u : まだ
git addしていないファイルを含む—staged / -S :
git addしているファイルのみその他のオプションは
man git-stashでmanページを確認
stash の一覧を確認:
git stash list stash@{0}: WIP on main: xxxxxxx comment-x stash@{1}: WIP on main: yyyyyyy comment-y ...- ファイル変更の一覧を確認できます。左の
stash@{0},stash@{1}が各変更・stash の名前です。
- ファイル変更の一覧を確認できます。左の
もっと stash の内容を見る:
git stash show- stash の内容を差分表示します。
git stash show --patchオプション —patch は -p でも可。
stash の内容をパッチ形式で表示します。
stash を適用(復元)する:
git stash pop <stash の名前>- stash の名前は
git stash listで確認。
- stash の名前は
stash を消去する:
# 全部消す git stash clear # 特定の stash を消す git stash drop <stash の名前>- stash の名前は
git stash listで確認。
- stash の名前は
git stash の使い方(応用)
stash を別のブランチへ移動する:
git checkoutでブランチを移動してからgit stash popで stash を適用すればよい。
stash を編集する:
# stash を適用する git stash pop stash@{0} # 変更を加える git stash [push] <options>pop で復元する stash の名前は
git stash listで確認。stash を適用し変更を加えた後に、新しい stash として保存。
stash をマージする:
git stash popで stash を適用した後、普通にgit add,git commitで変更をコミットすればよい。
参考文献
git stashのmanページman git-stashgit stash のドキュメント: https://git-scm.com/docs/git-stash
git の公式ページ: https://git-scm.com/

