0%

[實用git系列]改到一半想切去其他 branch 但又不想 commit 怎麼辦?

存狀態

首先在目前的 branch 終端機輸入

1
$ git stash

就會把有 modified 的變更先存起來,這時候 vscode 的 changes file 就會清空

接著就可以 git checkout <otherBranch>,到其他分支做事了

拿回狀態

那切回剛剛的 branch 後,要怎麼拿回剛剛存的狀態呢?

查看 stash 的狀態

我們先下 git stash list 看一下剛剛站存的檔案在哪

1
2
3
$ git stash list

stash@{0}: WIP on group: 2d3d9f8 <commit>

WIP 是 Work In Progress,group 是 branch name

如果在其他 branch 也進行 stash,git stash list 就會列出各個 branch 的 stash,pop 回來時可選定要拉哪個

拿回 stash 的狀態

重點來了,輸入以下指令

1
$ git stash pop stash@{0}

如果後面沒有指定要 pop 哪一個 Stash,會從編號最小的,也就是 stash@{0} 開始拿

1
$ git stash pop

成功之後,剛剛套用過的 stash@{0} 就會被刪除了

結論

stash 應用情境

  • 切到其他 branch 暫存檔案用
  • 想從遠端 pull 時,用 git stash 來暫存檔案,否則他會逼你先 commit 才能 pull

基本上,只要記得 $ git stashgit stash pop,就可以操作最基本的切換了,若要額外使用其他功能,如拿回狀態時不想從 stash list 刪掉,再去翻文章即可

git stash 的小衝突

這樣的,有一天 git pull後,修改了一些檔案,下班前用 git stash 暫存起來,隔天要 pop 回檔案時卻報錯了

下 git stash list

但是 workspace 明明是空的,看 git 報錯紀錄說是 edit-group.component.ts 這個檔案有衝突,點進去也沒說要改哪==

解決方式

https://stackoverflow.com/questions/19937580/cant-pop-git-stash-your-local-changes-to-the-following-files-would-be-overwri

最後使用

  1. 將 uncommitted changes stage 起來
    git add -u .

  2. 拉回暫存的內容
    git stash pop

  3. unstage 所有檔案
    git reset

參考文章

https://gitbook.tw/chapters/faq/stash.html