git stash 是 Git 中一个非常有用的命令,它可以临时保存当前工作区的修改,让你可以切换到其他分支或者处理其他任务,而不需要提交这些还未完成的修改。
1 |
git stash |
1 |
git stash list |
示例输出:
stash@{0}: WIP on main: 1234567 Fix bug
stash@{1}: WIP on feature-x: abcdef0 Add feature x
1 |
git stash pop |
1 |
git stash pop stash@{1} |
1 |
git stash apply stash@{1} |
1 |
git stash drop stash@{0} |
1 |
git stash clear |
1. 只 stash 暂存区和工作区中已修改的文件(不包括未追踪文件)
1 |
git stash -k # 等价于 git stash --keep-index |
2. 包括未追踪的文件一起 stash
1 |
git stash -u # 等价于 git stash --include-untracked |
3. 包括未追踪和忽略的文件一起 stash
1 |
git stash -a # 等价于 git stash --all |
4. 带描述信息
1 |
git stash save "WIP: 修复登录页面问题" |
注意:Git 2.15 之后推荐使用 git stash push -m "message" 代替 save。
假设你在 main 分支开发中临时要切换到 bugfix 分支修复紧急问题:
1 2 3 4 5 |
git stash # 保存当前未提交的代码 git checkout bugfix # 切换分支 ... # 修复并提交 git checkout main # 回到原分支 git stash pop # 恢复之前保存的代码 |