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

相关推荐
高调的涵涵1 天前
删了1.2GB,.git仍是1.2GB
git
程序员沉梦听雨1 天前
【Git】git-submodule子模块管理
git
全栈陈序员2 天前
Git】从入门到精通(八)—— git log:查看提交历史
大数据·git·elasticsearch
7177772 天前
Git自建用什么工具比较好:Gitea、Forgejo、GitLab CE与Gitee的选型对比
git·gitlab·gitea
lsc_blog3 天前
年底还在招的岗位,先确认缺口和到岗要求
git·缓存·ci/cd·职场和发展·github
全栈陈序员3 天前
【Git】从入门到精通(十一)—— git reset 三种模式详解
git·elasticsearch
全栈陈序员4 天前
【Git】从入门到精通(十)—— 撤销与恢复:git checkout与git restore
运维·网络·数据库·git
全栈陈序员4 天前
【Git】从入门到精通(五)—— git add:将文件加入暂存区
大数据·git·elasticsearch
全栈陈序员4 天前
【Git】从入门到精通(七)—— git status:查看仓库状态
大数据·git·elasticsearch
莫晓燚4 天前
Ansible 13 个常用模块---企业实战
git·github