开发学院

您的位置:首页>教程>正文

教程正文

Git Stash(暂存)操作

Git  Stash(暂存)操作

  假设你正在为你的产品实现一个新功能,你的代码正在进行中,突然出现客户升级。正因为如此,你不得不把你的新功能搁置几个小时。此时你既不能提交这部分代码,也不能丢弃这部分代码。因此,您需要一些临时空间,在那里您可以保存这部分代码,然后在合适的时候提交。

  在Git中,stash操作将当前工作区的修改暂存起来,就像堆栈一样,可以随时将某一次缓存的修改再重新应用到当前工作区。

[jerry@CentOS project]$ git status -s
M string.c
?? string

  现在,您想为客户升级而切换了分支,但是您不想提交您一直在做的事情,所以你会把这部分代码暂存起来。要将新的存储推到堆栈上,请运行git stash命令。

[jerry@CentOS project]$ git stash
Saved working directory and index state WIP on master: e86f062 Added my_strcpy function
HEAD is now at e86f062 Added my_strcpy function

  现在,您的工作目录是干净的,所有更改都保存在一个堆栈中。让我们用git status命令来验证它。

[jerry@CentOS project]$ git status -s
?? string

  现在你可以安全地切换分支到别处工作。我们可以使用git stash list命令查看暂存堆栈的列表。  

[jerry@CentOS project]$ git stash list
stash@{0}: WIP on master: e86f062 Added my_strcpy function

  假设您已经解决了客户升级问题,并且又回到了新的功能开发上来,为了寻找您的半成品代码,执行git stash pop命令,从堆栈中删除并将其放入当前的工作目录中。

[jerry@CentOS project]$ git status -s
?? string

[jerry@CentOS project]$ git stash pop

  上述操作产生如下输出:

# On branch master
# Changed but not updated:
# (use "git add ..." to update what will be committed)
# (use "git checkout -- ..." to discard changes in working directory)
#
#
modified: string.c
#
# Untracked files:
# (use "git add ..." to include in what will be committed)
#
#
string
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (36f79dfedae4ac20e2e8558830154bd6315e72d4)

[jerry@CentOS project]$ git status -s
M string.c
?? string