git stash 保存和恢复修改进度

张映 发表于 2018-08-08

分类目录: 技术其他

标签:, , , ,

我们有时会遇到这样的情况,正在dev分支开发新功能,做到一半时线上出严重bug,要马上解决,但是新功能做到了一半你又不想提交,这时就可以使用git stash命令先把当前进度保存起来,然后切换到主分支去修改bug,修改完提交后,再切回dev分支,使用git stash pop来恢复之前的进度继续开发新功能。下面来看一下git stash命令的常见用法和例子

1,git stash

保存当前工作进度,会把暂存区和工作区的改动保存起来。执行完这个命令后,在运行git status命令,就会发现当前是一个干净的工作区,没有任何改动。使用git stash save 'message...'可以添加一些注释

2,git stash list

显示保存进度的列表。也就意味着,git stash命令可以多次执行。

git stash pop [–index] [stash_id]
git stash pop 恢复最新的进度到工作区。git默认会把工作区和暂存区的改动都恢复到工作区。
git stash pop --index 恢复最新的进度到工作区和暂存区。(尝试将原来暂存区的改动还恢复到暂存区)
git stash pop stash@{1}恢复指定的进度到工作区。stash_id是通过git stash list命令得到的
通过git stash pop命令恢复进度后,会删除当前进度。

3,git stash apply [–index] [stash_id]

除了不删除恢复的进度之外,其余和git stash pop 命令一样。

4,git stash drop [stash_id]

删除一个存储的进度。如果不指定stash_id,则默认删除最新的存储进度。

5,git stash clear

删除所有存储的进度。

6,样例

MacBook-Pro:test zhangying$ git branch -a   //当前分支是主分支
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/dev
  remotes/origin/master

MacBook-Pro:test zhangying$ ls
aaa

MacBook-Pro:test zhangying$ git status   //查看一下状态
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean

MacBook-Pro:test zhangying$ vim aaa    //修改点内容

MacBook-Pro:test zhangying$ git checkout dev   //切换分支报错
error: Your local changes to the following files would be overwritten by checkout:
	aaa
Please commit your changes or stash them before you switch branches.
Aborting

MacBook-Pro:test zhangying$ git stash   //保存当前的修改进度,这样可以省去add,commit
Saved working directory and index state WIP on master: 299722c test commit y1.
HEAD is now at 299722c test commit y1.

MacBook-Pro:test zhangying$ git checkout dev  //可以切换分支了
Branch dev set up to track remote branch dev from origin.
Switched to a new branch 'dev'

MacBook-Pro:test zhangying$ git checkout master //切换回来
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

MacBook-Pro:test zhangying$ git stash list     //查看保存进度列表
stash@{0}: WIP on master: 299722c test commit y1.

MacBook-Pro:test zhangying$ git stash pop stash@{0}  //恢复进度,不加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:   aaa

no changes added to commit (use "git add" and/or "git commit -a")
Dropped stash@{0} (5f445e43c354449da33e4b9b4d2a912068ce34bb)   //pop后会删除,如果不想删除,用apply

MacBook-Pro:test zhangying$ cat aaa   //看一下,以前修改的东西是不是回来了。

 



转载请注明
作者:海底苍鹰
地址:http://blog.51yip.com/other/1945.html