什么是 Stashing

在处理项目时,当针对 master 生成错误时,你可能会在功能分支更改的中途完成。你尚未准备好提交代码,但你也不想丢失更改。这是 git stash 派上用场的地方。

在分支上运行 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:   business/com/test/core/actions/Photo.c

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

然后运行 git stash 将这些更改保存到堆栈:

(master) $ git stash
Saved working directory and index state WIP on master: 
2f2a6e1 Merge pull request #1 from test/test-branch
HEAD is now at 2f2a6e1 Merge pull request #1 from test/test-branch

如果你已将文件添加到工作目录,则这些文件也可以存储。你只需要先安排它们。

(master) $ git stash
Saved working directory and index state WIP on master:
(master) $ git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

        NewPhoto.c

nothing added to commit but untracked files present (use "git add" to track)
(master) $ git stage NewPhoto.c
(master) $ git stash
Saved working directory and index state WIP on master:
(master) $ git status
On branch master
nothing to commit, working tree clean
(master) $

你的工作目录现在已清除你所做的任何更改。你可以通过重新运行 git status 来看到这个:

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

要应用最后一个存储,请运行 git stash apply(此外,你可以应用删除最后一个用 git stash pop 更改的存储):

(master) $ git stash apply
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:   business/com/test/core/actions/Photo.c

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

但请注意,存储不记得你正在处理的分支。在上面的例子中,用户正在使用 master 。如果他们切换到 dev 分支, dev ,并运行 git stash apply,则最后一个存储被放在 dev 分支上。

(master) $ git checkout -b dev
Switched to a new branch 'dev'
(dev) $ git stash apply
On branch dev
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:   business/com/test/core/actions/Photo.c

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