跳到主要内容

Git stash 暂存现场指南

什么时候用

当你做到一半需要临时切换分支、处理紧急任务,或者现在还不想提交一堆半成品改动时,可以先把现场放进 stash

先判断当前状态

git status --short
git stash list
  • git status --short 用来确认当前有哪些改动。
  • git stash list 用来确认仓库里已经存了哪些现场。

推荐命令

场景推荐命令结果
暂存已跟踪改动git stash push -m "wip: message"保存当前现场,并恢复干净工作区
连未跟踪文件一起暂存git stash push -u -m "wip: message"额外包含新文件
查看 stash 列表git stash list查看所有暂存现场
查看某个 stash 具体改了什么git stash show -p stash@{0}显示差异
恢复并删除 stashgit stash pop应用成功后自动移除该 stash
恢复但保留 stashgit stash apply stash@{0}方便反复尝试
删除某个 stashgit stash drop stash@{0}手动清理不用的现场

常见场景

临时切到别的分支处理问题

git stash push -m "wip: refactor auth"
git switch main

回来后再恢复:

git switch feature/auth
git stash pop

把未跟踪文件也一起暂存

git stash push -u -m "wip: include new config"

默认情况下,git stash 不会包含未跟踪文件;需要 -u 才会一起带上。

先看看 stash 里有什么,再决定是否恢复

git stash list
git stash show -p stash@{0}
git stash apply stash@{0}

直接从 stash 拉一条新分支

git stash branch rescue-work stash@{0}

适合 stash 和当前分支已经偏离较多,不想直接在原分支上恢复的情况。

风险与边界

  • git stash 默认只保存已跟踪文件的改动;忽略文件需要 -a,未跟踪文件需要 -u
  • git stash pop 只有在应用成功时才会删除 stash;如果发生冲突,stash 通常会保留下来。
  • stash 是本地仓库里的现场,不会自动同步到远程。
  • 如果这份改动已经足够稳定,直接开分支或做一次正常提交,通常比长期堆 stash 更清晰。

相关命令

git stash list
git stash show -p stash@{0}
git stash apply stash@{0}
git stash drop stash@{0}