介绍
在团队开发中,在为功能分支编写代码的过程中,您经常需要切换分支来解决紧急的错误修复。
虽然您可以将半成品作为临时“WIP”提交提交,但更简洁的方法是使用 git stash。
本文介绍了高级 git stash 技术,包括保存未跟踪的文件、标记存储项目以及从存储中恢复特定文件。
1. git stash 的基础知识
让我们回顾一下最常用的命令:
# Save current changes (both staged and unstaged) to the stash stack
git stash
# List all saved stash entries
git stash list
# Restore the most recent stash entry (stash@{0}) and remove it from the stack
git stash pop
# Restore a stash entry without removing it from the stack
git stash apply
2. 先进的藏匿技术
① 包括未跟踪的文件(新文件)
默认情况下,git stash 仅保存对 Git 已跟踪的文件的更改。新创建的、未跟踪的文件会留在您的工作目录中。
要存储跟踪和未跟踪的文件,请添加 -u (--include-untracked) 标志:
# Save all changes, including newly created files
git stash -u
② 命名存储条目
当您保存多个存储条目时,列表可能会变得难以导航。您可以添加描述性消息来标识每个条目:
# Save a stash with a descriptive message
git stash push -m "WIP: login form styling"
③ 丢弃并清除存储堆栈
删除特定条目或清除整个堆栈以保持组织有序:
# Delete a specific stash entry (e.g., the second entry)
git stash drop stash@{1}
# Delete all entries from the stash stack (Note: this cannot be undone)
git stash clear
3. 从存储条目恢复特定文件
如果您只想从存储条目恢复单个文件(例如 config.json)而不是所有更改,则可以单独查看:
# Check out a specific file from the target stash entry
git checkout stash@{0} -- path/to/file.js
这会将指定的文件返回到您的工作目录,同时将剩余的更改保留在存储中。
结论
git stash 命令是在分支上下文切换期间管理工作目录的有效方法。
- 使用
git stash -u确保保存新创建的文件。 - 使用
-m标志添加描述以稍后识别条目。 - 使用
git checkout stash@{X} -- <path>有选择地恢复文件。
使用这些技术有助于防止代码丢失并保持分支历史记录干净。

