背景
在你新需求更改了一半的情况,测试突然跟你说生产环境有个bug,需要紧急处理;通常情况是多建一个文件夹,把生产分支代码拉下来直接更改;后面新需求更改完了,再把它合到生产分支。
但有没有不新拉分支,直接把本地的更改保存起来,后面处理完生产bug,再把更改拿回来,接着coding呢? git stash 就是干这个事的。
git stash把为commit的修改保存在本地,不会污染git tree;
常用命令
暂存
git stash 会把所有未提交的修改(包括暂存的和非暂存的)都保存起来,用于后续恢复当前工作目录。
对暂存加备注
git stash save 'xxx' ;同时可以组合使用 git stash save 'xxx' -p 指定文件暂存,且对暂存做备注;
部分暂存 参考
git stash -- filename指定单个文件暂存git stash -p一个交互式命令,会逐个询问每一处更改的处理方式
root /u/c/s/cbs (master)# git stash -p
diff --git a/cmd/scripts/cbs.sh b/cmd/scripts/cbs.sh
old mode 100644
new mode 100755
Stash mode change [y,n,q,a,d,/,?]?
这里的[y,n,q,a,d,/,?]分别代表的含义如下:
y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk nor any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk nor any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help
所以,遇到我们需要stash的文件,我们就 y ,不需要stash需要commit的文件,我们就 n ,如果接下来没有需要stash的文件,则直接 q 退出就行。
使用暂存
git stash apply stash@{xx}把对应暂存的更改应用到当前分支;直接git stash apply应用第一个暂存;git stash pop效果同上,区别是会删除对应暂存;
查看暂存
git stash list查看暂存列表;git stash show[ stash@{xx}[-p]]查看对应暂存对应的文件列表;不指定文件直接git stash show默认查看第一个暂存;加上-p则查看对应暂存的更改细节,查看过程同样是按q退出;
从stash创建分支
git stash branch testchanges
暂存未跟踪或忽略的文件
git stash -u暂存未跟踪的文件;git stash -a暂存所有更改,包含未跟踪和忽略的文件更改。