git

編集中の内容をgit stashで退避する手順

投稿日:

「gitlabでブランチを切ったのに、ローカルPCでブランチを切り替えず、masterやdevelopなどの主流ブランチでコード変更してしまった」

やってしまったらgit stashで変更を退避しておき、目的のブランチに切り替えてgit stash applyすることで本来の開発ブランチに変更を移します。

手順

あ、masterで作業してた。orz

$ git branch
  1-
  6-
* master

git statusでmasterの変更分を確認

$ git status
On branch master
Your branch is up-to-date with 'origin/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:   src/pages/gallery/actions.ts
        modified:   src/pages/gallery/gallery.html
        modified:   src/pages/gallery/gallery.scss
        modified:   src/pages/photo/actions.ts

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

git stashで変更を退避

$ git stash
warning: LF will be replaced by CRLF in www/build/main.css.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in www/build/main.js.
The file will have its original line endings in your working directory.
Saved working directory and index state WIP on master: bea9c4a Merge branch '6-' into 'master'
HEAD is now at bea9c4a Merge branch '6-' into 'master'

masterから退避されたことを確認

この時点でmasterを編集してしまった差分は無くなる。

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean

退避されたstashを確認

$ git stash list
stash@{0}: WIP on master: bea9c4a Merge branch '6-' into 'master'

本来の開発ブランチに移動

リモートを取り込めてなければ一度git fetch。

$ git fetch

$ git checkout 17-

$ git branch
  1-
* 17-
  6-
  master

git stash applyでstashした内容を目的のブランチに適用

$ git stash apply
On branch 17-
Your branch is up-to-date with 'origin/17-'.
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:   src/pages/gallery/actions.ts
        modified:   src/pages/gallery/gallery.html
        modified:   src/pages/gallery/gallery.scss
        modified:   src/pages/photo/actions.ts

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

masterで編集してしまった内容を、本来編集するはずだった17-ブランチに移動させることが出来ました。

焦らずにgit stashすれば大丈夫ですね。

-git
-

執筆者:

関連記事

GitLabのIPを変更したらMattermostにログイン出来なくなった話「the redirect uri included is not valid. 」

目次1 発端2 環境3 GitLabのIP変更設定を開始4 そしてハマる5 解決6 結局どこに設定が保存されていたか7 まとめ 発端 先日オフィスの引っ越しが有りネットワークセグメントが変わる為、Gi …

テキストファイル内の改行コード差異を見つけるワンライナー

ファイル内容は同じなのにdiffで違いが出るWeb上でソースレビューする時に同じ内容の行なのに差分が出て紛らわしい これらの原因はWindows、Mac、Linuxが入り混じった開発環境にあるかも知れ …

 

shingo.nakanishi
 

東京在勤、職歴2n年中年ITエンジニアです。まだ開発現場で頑張っています。

19歳(1996年)から書き始めたアウトプット用プライベートWeb日記数が5,000日を超え、残りの人生は発信をして行きたいと思い、令和元日からこのサイトを開始しました。勉強と試行錯誤をしながら、自分が経験したIT関連情報を投稿しています。

私と同じく、今後IT業界で生計を立てて行きたいと考えている方や、技術共有したいけど仲間が居なくて孤独、といった方と一緒に成長、知識共有して行けたら楽しいな、と思っています。