贮藏Stash
Git 专区暂时收起还没保存成版本的改动,需要时再取回
stash 让工作目录暂时恢复干净,方便切换分支或处理紧急任务。恢复可能产生冲突,未跟踪文件默认也不一定包含;它适合短期中转,不能代替有说明的 commit。
工作区index.html 改一半
git stash→
贮藏区stash@{0} 存起来
stash apply→
工作区救完火取回
$ git stash push -m "首页改到一半"
半成品整包塞进口袋,工作区立刻变干净,随便切分支救火;回来后 git stash apply 原样倒出来。stash 是临时中转,不是存档。
什么时候用
- 用带说明的 stash 临时保存未提交改动$ git stash push -m "首页改到一半"Saved working directory and index state On main: 首页改到一半
- 回来先 git stash apply:确认恢复正确后,再手动 drop$ git stash apply stash@{0}Changes restored to the working tree先保留 stash,确认恢复正确后再 drop
- 用 git stash list 查看已有记录及编号$ git stash liststash@{0}: On main: 首页改到一半stash@{1}: WIP on main: a1b2c3d 首页能跑了每存一次是一包,编号从 0 往上摞
- 塞的时候用 -m 起名字,三天后也认得这包是啥stash@{0}首页改到一半stash@{1}WIP on main: a1b2c3d起名字的包,一眼就知道装的是啥
什么时候不用
- 口袋只进不出攒了 8 包:stash 是中转站,不是仓库stash@{0} … stash@{7}攒了 8 包,最早的是上个月口袋只进不出,迟早变成垃圾堆
- 不看当前分支就 pop:首页的改动倒进了救火分支当前分支:hotfix/login$ git stash pop首页的改动倒进了救火分支!pop 之前先看自己在哪条线
- 三周前的包从没取过:里面装的啥谁也想不起来stash@{2}WIP on main: 三周前里面装的啥?谁也想不起来了
- 救完火凭记忆重做一遍:忘了口袋里有现成的半成品救完火回来,凭记忆重写了两小时…口袋里的半成品忘了 pop,白干一遍
组成结构 · Anatomy
🛠 工作区改到一半的 index.html
stash push →
stash@{0} 首页改到一半 ← 最新
stash@{1} WIP on main: a1b2c3d
stash@{2} WIP on main: 0f1e2d3
1工作区改动Working Dir还没 commit 的半成品,就是要被塞进口袋的那包
2最新一包stash@{0}最后一次 push 的改动,pop 默认取它
3往下摞stash@{1}每 push 一次,旧包编号加一,像一摞盘子
4更旧的包stash@{2}越往下越旧,记得尽快取,别攒成垃圾堆
常见变体 · Variants
存Push
git stash push -m "首页改到一半"
改到一半要切走,塞进口袋
看List
git stash list
忘了口袋里有几包时查
恢复Apply
git stash apply stash@{0}
先恢复但保留备份,确认后再 drop
取了留一份Apply
git stash apply
想倒出来看看,包还留着
典型使用场景
改到一半 stash push
$ git status
modified: index.html(改到一半)
⚡ 线上登录挂了,要切去 hotfix/login!
$ git stash push -m "首页改到一半"
Saved working directory and index state On main: 首页改到一半
$ git checkout hotfix/login
Switched to branch 'hotfix/login'
stash list 看暂存清单
$ git stash list
stash@{0}: On main: 首页改到一半
stash@{1}: WIP on main: a1b2c3d 首页能跑了
编号越小越新,pop 默认取 stash@{0}
stash apply 恢复
$ git checkout main
Switched to branch 'main'
$ git stash apply stash@{0}
On branch main
Changes not staged for commit:
modified: index.html
Changes restored to the working tree
改动已恢复,确认无误后再执行 drop
确认后 drop 清理
🛠 首页改到一半
stash push →
👖 口袋 stash@{0}
→ 救火 →
🛠 stash apply 恢复