Git 小技巧:用 `git stash` 把改动藏起来!

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 stashgit checkout
回到主分支合代码 git stashgit pullgit checkoutgit stash pop
临时改动太多想保存现场 git stash save "阶段性备份"

十、结语

git stash 是你的"代码备忘录",

在混乱和紧急任务中,它就像一只"时间胶囊",

让你随时暂停当前进度,又能毫无负担地重拾继续。

相关推荐
redreamSo6 小时前
长大后为什么时间越来越快?我们活的是记忆并非时间,人生是由故事组成的
程序员
唐叔在学习8 小时前
盘点IDEA中那些实用的GIT小技巧
程序员·intellij idea
周小董1 天前
[1336]python rich库
程序员
摆烂工程师1 天前
教你如何认证 Gemini 教育优惠的二次验证,薅个 1年的 Gemini Pro 会员
后端·程序员·gemini
考虑考虑1 天前
Redis8中的布谷鸟过滤器
redis·后端·程序员
我要改名叫嘟嘟1 天前
程序员找“出路”之写作读书满五年
程序员
文心快码 Baidu Comate1 天前
AI界的“超能力”MCP,到底是个啥?
人工智能·程序员·ai编程·文心快码·comate zulu
周小董1 天前
[1335]pyperclip模块安装和使用
程序员
摆烂工程师2 天前
Anthropic 停止 Claude 提供给多数股权由中国资本持有的集团或其子公司使用,会给国内的AI生态带来什么影响?
人工智能·程序员·claude