git stash

git stash 是 Git 的一个实用命令,用于临时保存当前工作目录和暂存区的修改,以便你可以切换到其他分支或任务,稍后再恢复这些更改。以下是关于 git stash 的详细说明和常见用法:


基本用法

  1. 保存当前修改(不包含未跟踪的文件)

    bash 复制代码
    git stash

    等价于:

    bash 复制代码
    git stash push
  2. 保存修改并包含未跟踪的文件(untracked files)

    bash 复制代码
    git stash -u

    或:

    bash 复制代码
    git stash --include-untracked
  3. 保存修改并包含所有文件(包括 ignored 文件)

    bash 复制代码
    git stash -a

    或:

    bash 复制代码
    git stash --all
  4. 添加说明信息(方便识别)

    bash 复制代码
    git stash save "描述信息"

查看存储的 stash 列表

bash 复制代码
git stash list

输出示例:

复制代码
stash@{0}: On main: 描述信息
stash@{1}: On feature-branch: WIP

恢复 stash

  1. 恢复最近一次的 stash 并删除 stash 记录(默认)

    bash 复制代码
    git stash pop
  2. 恢复指定 stash(不删除记录)

    bash 复制代码
    git stash apply stash@{n}

    例如:

    bash 复制代码
    git stash apply stash@{0}
  3. 恢复 stash 并删除记录

    bash 复制代码
    git stash pop stash@{n}

删除 stash

  1. 删除最近一次的 stash

    bash 复制代码
    git stash drop
  2. 删除指定的 stash

    bash 复制代码
    git stash drop stash@{n}
  3. 清空所有 stash

    bash 复制代码
    git stash clear

进阶用法

  1. 将 stash 应用到其他分支

    • 先切换到目标分支,再运行 git stash apply
  2. 从 stash 创建新分支

    bash 复制代码
    git stash branch 新分支名 stash@{n}

    这会基于 stash 的提交创建一个新分支,并自动删除该 stash。

  3. 查看 stash 的差异

    bash 复制代码
    git stash show -p stash@{n}

常见场景示例

场景 1:临时切换分支
bash 复制代码
# 当前有未提交的修改
git stash
git checkout 其他分支
# 完成其他任务后切回原分支
git checkout 原分支
git stash pop
场景 2:保存未完成的实验性代码
bash 复制代码
git stash save "实验性功能A的部分代码"
# 后续恢复
git stash pop
场景 3:误删 stash 后恢复

如果误删了未备份的 stash,可以通过 Git 的引用日志找回:

bash 复制代码
git fsck --unreachable | grep commit | awk '{print $3}' | xargs git show
# 找到对应的提交后,手动恢复

注意事项

  1. 冲突处理

    如果 popapply 时发生冲突,需手动解决冲突后提交。

  2. 未跟踪文件

    默认不保存未跟踪文件(需加 -u-a 参数)。

  3. 长期存储

    Stash 是临时存储,长期未使用的 stash 可能会被垃圾回收(建议提交到分支)。

  4. 安全性

    敏感数据(如密码)不建议存到 stash,可能通过日志泄露。


通过灵活使用 git stash,你可以高效管理临时修改,避免不必要的提交或丢失工作进度!

相关推荐
hh随便起个名3 小时前
适合小白的git的基础使用方法
git
我会一直在的3 小时前
Devps持续集成
git·ci/cd
CoderJia程序员甲4 小时前
GitHub 热榜项目 - 日榜(2026-02-08)
git·ai·开源·llm·github
Serene_Dream6 小时前
git 常用命令
git
jiayong236 小时前
Detached HEAD 状态详解
git
李少兄15 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
先跑起来再说21 小时前
Git 入门到实战:一篇搞懂安装、命令、远程仓库与 IDEA 集成
ide·git·后端·elasticsearch·golang·intellij-idea
承渊政道1 天前
Linux系统学习【Linux系统的进度条实现、版本控制器git和调试器gdb介绍】
linux·开发语言·笔记·git·学习·gitee
Doro再努力1 天前
【Linux操作系统12】Git版本控制与GDB调试:从入门到实践
linux·运维·服务器·git·vim
摇滚侠1 天前
MAC IDEA GIT 提交区显示了几个不存在的目录
git·idea