721 文字
4 分
【Git】変更の一時退避 stash サブコマンド

git stash コマンドを使ってファイルの変更を一時退避#

git stash とは#

git stash コマンドは、Git における作業フローを柔軟にする強力なツールです。基本的な使い方といくつかの応用例を解説します。

Use git stash when 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-stashman ページを確認

  • 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 を消去する:

    # 全部消す
    git stash clear
    
    # 特定の stash を消す
    git stash drop <stash の名>
    
    • stash の名前は git stash list で確認。

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 サブコマンド
https://memos-and-essays.pages.dev/posts/git-stash/
作者
Hiiro Yasaka
公開日
2024-08-18
ライセンス
CC BY 4.0