Git 小技巧:用 git stash
把改动藏起来!
你有没有遇到这种情况?
正在修改一堆文件,突然要切换分支处理另一个紧急任务,可是又不想 commit......
这时候脑子里只有一个念头:
"我能不能先把这些改动藏起来,等会儿再拿回来?"
没错,这就是 git stash
大显神通的时候!
一、什么是 git stash
?
通俗点讲:
git stash
会把你工作区的未提交改动 (包括新增、修改、删除的内容)"临时存起来",然后让你的工作目录恢复到"干净"的状态。
你可以:
- 切换分支 💨
- 拉代码更新 🔄
- 处理紧急 bug 🔥
等你忙完了,再把刚才"藏起来的改动"拿回来继续改!👌
二、快速上手示例
1. 你在干活:
bash
echo "未完成的功能" >> feature.txt
改了一些东西,还没 commit。
2. 突然来了个紧急任务,要切换分支?
这时候你运行:
git stash
终端显示:
perl
Saved working directory and index state WIP on main: 7f3cabc 添加 hello.txt 文件
你的改动就被"藏起来"了!
运行:
lua
git status
输出会显示:工作目录干净!
三、改动去哪儿了?
git stash list
你会看到:
less
stash@{0}: WIP on main: 7f3cabc 添加 hello.txt 文件
说明你的改动在 stash 里排第一位。
四、怎么拿回来?
git stash apply
它会把最新一次 stash 的改动还原回来(不删除 stash)。
或者你想取出并从列表中移除这个 stash,用:
perl
git stash pop
⚠️ 注意:apply
会留下 stash 副本,pop
会取出并删除。
五、有多个 stash 怎么办?
你可以用编号:
kotlin
git stash apply stash@{1}
六、stash 也可以命名!
方便管理,用这个命令:
arduino
git stash save "修复登录页面样式"
再运行:
git stash list
你会看到备注内容,比默认的 WIP
更清楚!
七、stash 删除和清空
清理掉某个 stash:
kotlin
git stash drop stash@{0}
全部清除:
arduino
git stash clear
八、总结小抄
命令 | 说明 |
---|---|
git stash |
把当前改动临时存起来 |
git stash apply |
还原最近一次 stash |
git stash pop |
还原并删除 stash |
git stash list |
查看 stash 列表 |
git stash show |
查看某个 stash 修改了哪些文件 |
git stash clear |
清空所有 stash |
git stash save "备注" |
添加带说明的 stash |
九、使用场景举例
场景 | 推荐操作 |
---|---|
急着切换分支但不想 commit | git stash → git checkout |
回到主分支合代码 | git stash → git pull → git checkout → git stash pop |
临时改动太多想保存现场 | git stash save "阶段性备份" |
十、结语
git stash
是你的"代码备忘录",在混乱和紧急任务中,它就像一只"时间胶囊",
让你随时暂停当前进度,又能毫无负担地重拾继续。