設想一下開發中以下的一種情景,當你在一個分支 work 上開發一個新功能時候,原來的程序報了一個序號為101的 bug,急需修復,而手頭上的工作還未完成,不能提交。這時候我們該怎么辦呢?
方法是先把手頭上的工作“掩埋”起來,然后建一個分支 issue-101 去修復 bug,待 bug 修復完成后再著手手頭上的工作。
請看下面一個例子:
創建一個分支 work,把正在做的工作的 commit 提交到這個分支上:
$ git checkout -b work
$ git add test.txt
$ git commit -m '工作中'
這時出現了一個 bug,我們先放下當前的工作,用 git stash 命令把手頭上的工作“掩埋”起來:
$ git stash
Saved working directory and index state WIP on work: 58951c7 工作中
HEAD is now at 58951c7 工作中
注意:這里只修改了工作區的內容,并沒有執行 git add 和 git commit。
然后我們就可以回到 master,新建一個分支 issue-101 來修復這個 bug:
$ git checkout master
$ git checkout -b issue-101
把 bug 修復,然后提交:
$ git add test.txt
$ git commit -m "已修復 bug 101"
修復完成后,切換到 master 分支,并完成合并,最后刪除 issue-101 分支:
$ git checkout master
$ git merge --no-ff -m "修復 bug 101,并合并到 master" issue-101
$ git branch -d issue-101
現在 bug 已經修復完了,我們要回到 work 分支,繼續剛才的工作:
$ git checkout work
Switched to branch 'work'
$ git status
# On branch work
nothing to commit (working directory clean)
現在工作區是空的,我們先用 git stash list 命令看看:
$ git stash list
stash@{0}: WIP on work: 58951c7 工作中
工作現場還在,Git 把 stash 內容存在某個地方了,但是需要恢復一下,有兩個辦法:
一是用 git stash apply 恢復,但是恢復后,stash 內容并不刪除,你需要用 git stash drop 來刪除;
另一種方式是用 git stash pop,恢復的同時把stash內容也刪了:
$ git stash pop
On branch work
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: test.txt
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (a801931f6ab2e061167bf0ed85bb9522928f29f7)
如果有多次 stash,恢復的時候,先用 git stash list 查看,然后恢復指定的stash:
$ git stash apply stash@{0}