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       # 恢复之前保存的代码

相关推荐
凯尔萨厮5 小时前
Git(学习笔记)
笔记·git·学习
一技安身8 小时前
【Git】零基础入门实战教程(Windows 完整版,适配竞赛仓库)
windows·git
LXY_BUAA10 小时前
Git_在飞牛中部署 GitLab_20260817
git·gitlab
阳墨余12 小时前
Git 同时管理 Gitee 和 GitHub 的 SSH 配置实战
git·gitee·github
fengyehongWorld20 小时前
Git 认证凭据管理
git
暮云星影1 天前
git版本发布
git·gitee·github·gitea
乌夷1 天前
Git Flow 分支模型
git
独隅1 天前
VS Code Git 工作树多分支并行开发实战评测
git
暮云星影1 天前
git仓库分支管理
git·gitee·github·gitea
互联网中的一颗神经元2 天前
ZZ — Git 速查表
大数据·git·elasticsearch