0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Git】stash の中身確認・差分表示・特定ファイルだけを戻すテクニックまとめ

Posted at

はじめに

Git を使って開発していると、「ちょっとこの作業を一旦退避したい!」という場面が多々あります。そんなとき便利なのが git stash です。
本記事では、stash の基本的な使い方に加えて、

  • stash の中身の確認方法
  • 特定ファイルだけを戻す方法
  • stash 内のファイルと現在のファイルの差分確認
    といった、知っておくと便利なコマンドをまとめました。

基本:stash の一覧確認

まずは stash の一覧を確認しましょう。

git stash list

出力例:

stash@{0}: WIP on main: abc1234 修正作業中
stash@{1}: WIP on main: def5678 別の修正

stash の中身を確認したい(概要と詳細)

概要を確認する(どのファイルが変わっているか)

git stash show stash@{0}

stash@{0} の部分は、git stash list で確認したものに置き換えてください。

差分の詳細を確認する(実際の変更内容)

git stash show -p stash@{0}

stash 内の特定ファイルと現在のファイルの差分を確認する

git diff stash@{0} -- path/to/file.txt

これで、stash@{0} に保存された file.txt と現在の作業ディレクトリにある file.txt の違いを確認できます。

stash から特定のファイルだけを戻す方法

git stash pop は stash の内容をすべて適用し、削除しますが、「特定ファイルだけ戻したい!」場合は以下の方法を使います。

1. スタッシュ内容を消さずに一時適用

git stash apply stash@{0}

stash pop ではなく apply を使うことで、stash の中身を保持したまま適用できます。

2. 特定ファイルのみを戻す

git checkout stash@{0} -- path/to/file.txt

これにより、stash 内の file.txt だけを作業ツリーに反映できます。

3. 不要になった stash を削除

git stash drop stash@{0}

便利ワンライナー:すべての stash の内容を表示する

git stash list | while read -r stash; do echo $stash; git stash show -p ${stash%%:*}; done

全 stash の差分をまとめて確認できます。

まとめ

操作内容 コマンド例
stash 一覧 git stash list
内容の概要確認 git stash show stash@{0}
差分の詳細確認 git stash show -p stash@{0}
特定ファイルの差分 git diff stash@{0} -- path/to/file.txt
特定ファイルのみを戻す git checkout stash@{0} -- path/to/file.txt
stash を適用(削除せず) git stash apply stash@{0}
stash を削除 git stash drop stash@{0}

おわりに

Git stash は「一時避難」の強力な武器ですが、うまく使いこなせば 柔軟な作業切り替えや差分確認 にも使えます。とくに複数人開発や CI 連携の場面では「ファイル単位で戻す」テクニックが役立ちます。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?