LoginSignup
79
48

More than 3 years have passed since last update.

[Git] ファイル単位でstashする

Last updated at Posted at 2019-07-11

 
〜ローカルリポジトリで作業中〜

 
ワイ 「よ〜し作業終わったしcommitするゾ!」


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:   fuga.py
	modified:   hoge.py

no changes added to commit (use "git add" and/or "git commit -a")

 

ワイ 「branch切り替えるのを忘れてmasterを変更してもうた・・・」

ワイ 「featureブランチに変更を移したい。。。」

git stash

そんな時に使えるのがgit stash
ファイルを一時的に退避させることができる。
もちろんbranch間の移動も可能なので無理やり汚いcommitをする必要もない。

$ git stash
Saved working directory and index state WIP on master: e1c4afb [feat] hoge.py fuga.py

$ git status
On branch master
nothing to commit, working tree clean

$ git stash list
stash@{0}: WIP on master: e1c4afb [feat] hoge.py fuga.py

こんな感じで変更が退避されて$ git stash listで確認することができる
他のbranchに適用させたい時は以下のようにする

$ git checkout feature/hogefuga
Switched to branch 'feature/hogefuga'

$ git status
On branch feature/hogefuga
nothing to commit, working tree clean

$ git stash pop
On branch feature/hogefuga
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:   fuga.py
	modified:   hoge.py

no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (0706e9eb4284f2fcd1bb6ac6a049beb0e52ffdb6)

おけまる!

ファイル単位でstashしたい

特定のファイルだけ別のbranchに移動させたいという場合もあるだろう。
$ git stashだけだと変更の及んだ全てのファイルがstashされてしまう。
ファイル単位でstashするには以下のようにする。

// 退避する時
$ git stash push -- <filepath>

// 戻す時(番号はstash番号)
$ git stash pop stash@{0}

実際にやってみたのが以下

$ git branch
  develop
  feature/hogefuga           // ここにfuga.pyを移動
  feature/hogehogefugafuga   
* master                     // hoge.py fuga.py
$ git stash push -- hoge.py
Saved working directory and index state WIP on master: e1c4afb [feat] hoge.py fuga.py

$ git stash push -- fuga.py
Saved working directory and index state WIP on master: e1c4afb [feat] hoge.py fuga.py

$ git stash list
stash@{0}: WIP on master: e1c4afb [feat] hoge.py fuga.py
stash@{1}: WIP on master: e1c4afb [feat] hoge.py fuga.py

$ git checkout feature/hogefuga
Switched to branch 'feature/hogefuga'

$ git stash pop stash@{0} # fuga.py
On branch feature/hogefuga
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:   fuga.py

no changes added to commit (use "git add" and/or "git commit -a")
Dropped stash@{0} (3c71ae19147fc1ef56a748df9fe849471f933956)

できた!

終わりに

stash自体まだまだ便利なオプションとかあるのでそこは各自で調べてもらえると嬉しいです。
快適なgitライフを送りましょう!

79
48
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
79
48