设想一下开发中以下的一种情景,当你在一个分支 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}