一 场景
大家应该碰见过这样的情况,在一个分支上做一个开发任务,进行中时要求修改一个紧急bug。比较尴尬的是,代码写了部分修改比较多,不能提交,要修改的bug可能涉及到已修改的文件,并且要先提交。以前只能先将涉及的文件备份后revert,然后修改bug,最后只提交bug修复的代码,再手动将备份代码加回来。很不方便,并且容易出错。git上有个stash命令适用该情况
二 操作
1 在dev1分支上修改test.txt文件,增加内容aaaaaaaaaaa
2 test.txt当前内容如下:
3 执行 git stash命令
此时查看状态,工作区没有修改(修改被隐藏了)
4 此时再修改test.txt,增加内容bbbbbbbb,如下
此时状态,
提交,
相当于bug修复的文件提交完成了。
5 恢复修改,两种方法
(1)git stash apply恢复,但stash内容并不删除,需要再使用git stash drop命令来删除。可用 git stash list查看stash内容。
(2)使用git stash pop命令,恢复的同时把stash内容也删除了。
我采用git stash pop命令
恢复后,打开test.txt,此时有冲突,
手动解决冲突,
最后提交
--------------------------2021.09.17 add
可以stash多次,如何恢复指定版本的stash呢? 举例如下:
1. 修改a.txt,然后第一次stash
lee@leedeMacBook-Pro git_learn % 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 restore <file>..." to discard changes in working directory)
modified: a.txt
no changes added to commit (use "git add" and/or "git commit -a")
lee@leedeMacBook-Pro git_learn % git diff
diff --git a/a.txt b/a.txt
index e69de29..9606d7d 100644
--- a/a.txt
+++ b/a.txt
@@ -0,0 +1 @@
+aaaaaaaaa
\ No newline at end of file
lee@leedeMacBook-Pro git_learn % git stash
Saved working directory and index state WIP on master: 4d67665 Merge branch 'test1'
lee@leedeMacBook-Pro git_learn % git status
On branch master
2 然后修改a.txt, 第二次stash
lee@leedeMacBook-Pro git_learn % 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 restore <file>..." to discard changes in working directory)
modified: a.txt
no changes added to commit (use "git add" and/or "git commit -a")
lee@leedeMacBook-Pro git_learn % git diff
diff --git a/a.txt b/a.txt
index e69de29..c764de5 100644
--- a/a.txt
+++ b/a.txt
@@ -0,0 +1 @@
+Bbbbbb
\ No newline at end of file
lee@leedeMacBook-Pro git_learn % git stash
Saved working directory and index state WIP on master: 4d67665 Merge branch 'test1'
3. 此时查看下stash的情况, git stash list 发现有两个记录:
lee@leedeMacBook-Pro git_learn % git stash list
stash@{0}: WIP on master: 4d67665 Merge branch 'test1'
stash@{1}: WIP on master: 4d67665 Merge branch 'test1' // index越大越旧
4. 恢复第一次stash的内容 git stash pop stash@{1}
lee@leedeMacBook-Pro git_learn % git stash pop stash@{1}
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 restore <file>..." to discard changes in working directory)
modified: a.txt
no changes added to commit (use "git add" and/or "git commit -a")
Dropped stash@{1} (087e9bd94e1452dd31b5a3894cb116325ef01b94)
lee@leedeMacBook-Pro git_learn % git diff
diff --git a/a.txt b/a.txt
index e69de29..9606d7d 100644
--- a/a.txt
+++ b/a.txt
@@ -0,0 +1 @@
+aaaaaaaaa
\ No newline at end of file
lee@leedeMacBook-Pro git_learn %