Git 实用命令:git stash 让你在分支间切换自如,工作更高效

git branch 、git checkout 、git commit 、git pull 、git push,这些基本的 Git 命令,大家肯定不陌生。

今天我再分享一个开发过程中比较实用的命令,可以大大提高工作效率,解决疑难场景,让我们开始吧。

git stash

stash 命令能够将还未 commit 的代码暂存起来,让你的工作目录变干净。

应用场景

你正在 feature 分支开发新功能,突然你的领导告诉你线上有 bug,必须马上修复。

此时新功能开发到一半,你又要切换到 master 分支修复 bug,这时就会报错:

error: Your local changes to the following files would be overwritten by checkout:
  src/pages/.../index/index.tsx
Please commit your changes or stash them before you switch branches.
Aborting

因为当前有文件更改了,需要提交 commit 保持工作区干净才能切分支,于是提交记录就留了一条黑历史。。。

命令使用

git stash

这样代码就被存起来了,当你修复完线上问题,切回 feature 分支,想恢复代码也只需要:

git stash pop

相关命令

git stash
# 保存当前未 commit 的代码

git stash save "备注的内容"
# 保存当前未 commit 的代码并添加备注

git stash list
# 列出 stash 的所有记录

git stash clear
# 删除 stash 的所有记录

git stash apply
# 应用最近一次的 stash

git stash pop
# 应用最近一次的 stash ,随后删除该记录

git stash drop
# 删除最近的一次 stash

当有多条 stash,可以指定操作 stash,首先使用 stash list 列出所有记录:

$ git stash list
stash@{0}: WIP on ...
stash@{1}: WIP on ...
stash@{2}: On ...

应用第二条记录:

$ git stash apply stash@{1}

pop,drop 同理。


未经允许不得转载:w3h5前端开发资源网 » Git 实用命令:git stash 让你在分支间切换自如,工作更高效

赞 (0)