git stash命令用法

git stash 是 Git 中一个非常有用的命令,它可以临时保存当前工作区的修改,让你可以切换到其他分支或者处理其他任务,而不需要提交这些还未完成的修改。


一、基本用法

1. 保存当前修改(包括暂存区和工作区的内容)
bash 复制代码
git stash
2. 查看保存了哪些 stash
bash 复制代码
git stash list

示例输出:

复制代码
stash@{0}: WIP on main: 1234567 Fix bug
stash@{1}: WIP on feature-x: abcdef0 Add feature x
3. 恢复最近一次 stash 并删除它
bash 复制代码
git stash pop
4. 恢复某一个 stash 并删除它
bash 复制代码
git stash pop stash@{1}
5. 恢复某一个 stash 但保留
bash 复制代码
git stash apply stash@{1}
6. 删除某一个 stash
bash 复制代码
git stash drop stash@{0}
7. 清除所有 stash
bash 复制代码
git stash clear

二、常见增强用法

1. 只 stash 暂存区和工作区中已修改的文件(不包括未追踪文件)
bash 复制代码
git stash -k   # 等价于 git stash --keep-index
2. 包括未追踪的文件一起 stash
bash 复制代码
git stash -u   # 等价于 git stash --include-untracked
3. 包括未追踪和忽略的文件一起 stash
bash 复制代码
git stash -a   # 等价于 git stash --all
4. 带描述信息
bash 复制代码
git stash save "WIP: 修复登录页面问题"

注意:Git 2.15 之后推荐使用 git stash push -m "message" 代替 save


三、举个例子

假设你在 main 分支开发中临时要切换到 bugfix 分支修复紧急问题:

bash 复制代码
git stash           # 保存当前未提交的代码
git checkout bugfix # 切换分支
...                 # 修复并提交
git checkout main   # 回到原分支
git stash pop       # 恢复之前保存的代码

相关推荐
CV资深专家3 小时前
常用git命令
git
bug和崩溃我都要5 小时前
Git提交代码完整流程
git
逢考必过@k6 小时前
git的使用
git
狂炫一碗大米饭11 小时前
如何在 Git 中检出远程分支
前端·git·github
dolzhuying12 小时前
git常见场景食用指南
git
上邪o_O13 小时前
Git 的基本使用指南(1)
linux·git
飏旎1 天前
git pull和git fetch的区别
git
z涛.1 天前
git的使用
git
大卫小东(Sheldon)2 天前
智能生成git提交消息工具 GIM 发布 1.7 版本了
git·ai·rust
慧都小项2 天前
UI测试平台TestComplete如何实现从Git到Jenkins的持续测试
git·ui·jenkins·代码质量·testcomplete·zephyr for jira