如何在Git中将某些文件不是全部从一个分支移动到另一个分支?

问题描述

碰巧,在一个错误地进行代码修复的分支中,我开始进行与另一个分支相对应的一些更改(修改创建文件)。您如何将某些特定文件一个分支传递到另一个分支?谢谢!

解决方法

最简单的方法是stash进行更改,移至正确的分支,然后应用隐藏的更改。请注意,stash默认为push子命令,因此git stashgit stash push是等效的。

git stash [<pathspec>...] # store the changes in the current tree
git switch <correct_branch>  # move to the proper branch (use checkout if git < 2.23)

# apply the changes to the correct branch
git stash apply
git stash drop

您可以将最后两行合并为git stash pop,唯一的区别是隐藏已自动删除,并且如果由于某种原因需要再次使用它,您将无法访问它。