正确做法是先执行 git stash save "wip: feature/login" 暂存未提交修改,确认 git status 显示工作树干净后,再 git checkout main 切换分支;新增未跟踪文件需加 -u 参数。

git stash 保存未提交修改再切分支
直接 git checkout 切到 main 或 master 会失败,报错 error: Your local changes to the following files would be overwritten by checkout —— Git 拒绝覆盖你还没提交的改动。
这时候不能硬切(比如用 git checkout -f),否则未暂存的修改就丢了。正确做法是先暂存:
-
git stash save "WIP: feature/login"—— 建议加描述,方便后续识别 -
git status确认输出nothing to commit, working tree clean - 再
git checkout main就能成功切换
注意:git stash 默认只保存已跟踪文件的修改;新增但未 git add 的文件不会被保存,需要加 -u 参数(git stash -u)才包含未跟踪文件。
从 main 创建 hotfix 分支并修复提交
不要在 main 上直接改,必须新建分支。热修复分支命名建议统一,比如 hotfix/xxx 或 fix/xxx,便于识别和自动化处理。
-
git pull origin main—— 先同步远程最新,避免基于旧代码修复 git checkout -b hotfix/login-null-pointer- 改代码 →
git add .→git commit -m "fix: avoid NPE in login handler"
修复完成后别急着合并。先本地跑一遍关键测试,尤其是复现 bug 的用例;如果项目有 CI,推上去等流水线通过再继续。
合并 hotfix 到 main 和 develop 后清理
合并时要用 --no-ff,否则 fast-forward 合并会丢失分支信息,后续查问题难定位。
-
git checkout main→git merge --no-ff -m "merge hotfix/login-null-pointer" hotfix/login-null-pointer -
git tag -a v2.1.3 -m "hotfix: login NPE"→git push origin main --tags -
git checkout develop→git merge --no-ff -m "chore: sync hotfix/login-null-pointer" hotfix/login-null-pointer
develop 合并 hotfix 是必须步骤:否则下次发版把 develop 合入 main 时,这个修复就被覆盖回去了。别跳过。
切回原分支并恢复工作现场
git stash pop 不等于“一定成功”。如果原分支自上次 stash 后也改过相同文件,pop 时会冲突 —— 这时候 Git 不会自动 abort,而是把冲突标记留在工作区,得手动解决。
- 先
git checkout feature/login -
git stash pop→ 如果提示 conflict,就按常规方式编辑冲突文件、git add、git commit - 若想预览 stash 内容再决定是否 pop:
git stash show -p
stash 是栈结构,pop 取走最近一次;如果中途又 stash 过多次,要用 git stash list 查编号,再 git stash apply stash@{1} 指定恢复。











