Git教程
Git标签管理
Git分支
Git操作
Git应用
GitHub应用
IDEA对于Git&GitHub的支持
Git与GitHub使用注意事项

Git隐藏(Stash)操作

假设您正在为产品新的功能编写/实现代码,当正在编写代码时,突然出现软件客户端升级。这时,您必须将新编写的功能代码保留几个小时然后去处理升级的问题。在这段时间内不能提交代码,也不能丢弃您的代码更改。 所以需要一些临时等待一段时间,您可以存储部分更改,然后再提交它。

在Git中,隐藏操作将使您能够修改跟踪文件,阶段更改,并将其保存在一系列未完成的更改中,并可以随时重新应用。

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

        modified:   main.py

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

现在,要切换分支以进行客户升级,但不想提交一直在做的工作; 那么可以把当前工作的改变隐藏起来。 要将一个新的存根推到堆栈上,运行git stash命令。

$ git stash
Saved working directory and index state WIP on master: ef07ab5 synchronized with the remote repository
HEAD is now at ef07ab5 synchronized with the remote repository

现在,工作目录是干净的,所有更改都保存在堆栈中。 现在使用git status命令来查看当前工作区状态。

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

nothing to commit, working directory clean

现在,可以安全地切换分支并在其他地方工作。通过使用git stash list命令来查看已存在更改的列表。

$ git stash list
stash@{0}: WIP on master: ef07ab5 synchronized with the remote repository

假设您已经解决了客户升级问题,想要重新开始新的功能的代码编写,查找上次没有写完成的代码,只需执行git stash pop命令即可从堆栈中删除更改并将其放置在当前工作目录中。

$ git status -s

Administrator@MY-PC /D/worksp/sample (master)

[jerry@CentOS project]$ git stash pop

上述命令将产生以下结果:

$ git stash pop
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

        modified:   main.py

no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (e713780380632c142ed5833a9087aca883a826fa)

Administrator@MY-PC /D/worksp/sample (master)

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

        modified:   main.py

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

可以看到,工作区中修改的文件(main.py)又显示了。现在我们就可以继续编写上次编写了未完成的代码。

全部教程