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

相关推荐
CoderJia程序员甲4 小时前
GitHub 热榜项目 - 日榜(2025-12-15)
git·ai·开源·llm·github
大柏怎么被偷了4 小时前
【Git】远程操作
git
studytosky5 小时前
Linux 基础开发工具(3):Git 控制与 GDB 调试实用指南
linux·运维·服务器·网络·数据库·git
云闲不收6 小时前
AI编程系列——git-worktree并行开发
git·ai编程
秦时明月天明6 小时前
GitLab SSH Key 过期:git pull failed : remote your ssh key has expired
git·ssh·gitlab
桃花岛主707 小时前
命令提交git到github上的步骤
git·github
AI逐月7 小时前
Git 停止追踪已提交文件问题
大数据·git·elasticsearch
是毛毛吧7 小时前
开发环境配置指南:解决 GitHub 连接超时与依赖下载失败的问题
网络·git·网络安全·docker·信息与通信
bj_zhb8 小时前
git stash 用法
git
rockmelodies8 小时前
本地 PyCharm 生成的 Git 仓库与 GitHub 远程仓库关联起来
git·pycharm·github