你不知道的git操作之stash

110 阅读2分钟

前言

在工作中,大家在写代码时遇见过正在自己分支上写着代码,然后有反馈说主分支上有个问题需要修复,当前分支上的代码又没有完成,需要先去解决主分支上的代码,此时有人就想着把修改的文件复制一份或重新拉取一个本地,其实 git 还有更方便的解决方案 —— git stash 。

stash 常用命令

常用的命令在 VS Code 编辑器中都已经集成,在下面来先看下 stash 相关的命令。

stash 常用命令

git-stash.png

git stash & git stash (Include untracked)

对当前工作区的代码进行存储。 git stashgit stash (Include Untracked) 区别在于 include untracked 这个会将新建的文件也进行存储,新文件是 git 之前没有记录的。 点击 stash 进行存储时会有个输入框弹出用于提交 stash message ,这个也是方便在后续读取删除时方便查询。

git stash apply & git stash pop

存了之后就是读取之前的记录了。 git stash applygit stash pop 区别就像是 apply 是复制,pop 是剪切。

git stash drop

这个就是删除存储的记录操作。

知其所以然,对应的命令行操作

命令行和可视化操作喜欢什么就用什么,我没有任何意见。

// 查询现有的 stash
git stash list
// 读取内容展示
stash@{0}: 最新的一条记录
stash@{1}: 最新的前一条记录

// 新增
git stash save "stash message"
git stash save "stash message" -u | --include-untracked

// 读取
git stash apply // 复制读取最新的一条
git stash apply stash@{0} // 复制读取最新的一条
git stash pop // 读取最新的一条
git stash pop stash@{0} // 读取最新的一条

// 删除(慎重)
git stash drop stash@{0}
git stash clear

没使用过亲自试一下就明白了,have fun ~