在使用 Git 合并(git merge
)时,默认会将所有的更改合并到当前分支。如果你只想合并部分文件而不是整个提交,你可以使用几种方法来实现这一目标。
方法一:使用 git checkout
(或 git restore
)
你可以通过 git checkout
(在 Git 2.23 及之后版本中是 git restore
)来仅合并特定的文件。这个方法允许你从目标分支中选择性地将文件合并到当前分支。
操作步骤:
- 切换到你的目标分支(通常是要合并的那个分支):
bashCopy Code
git checkout <target-branch>
- 切换回你想要合并到的分支:
bashCopy Code
git checkout <current-branch>
- 从目标分支选择性地恢复某些文件:
bashCopy Code
git checkout <target-branch> -- path/to/file1 path/to/file2
或者在 Git 2.23 及之后的版本中,使用:
bashCopy Codegit restore --source=<target-branch> path/to/file1 path/to/file2
- 添加和提交更改:
bashCopy Code
git add path/to/file1 path/to/file2 git commit -m "Merged specific files from <target-branch>"
方法二:使用 git cherry-pick
(适用于单个提交)
如果你只想合并目标分支中的某个提交,可以使用 git cherry-pick
来选择性地应用特定的提交。
操作步骤:
- 查看目标分支上的提交历史:
bashCopy Code
git log <target-branch>
- 选择你想要合并的提交,记下其提交哈希值。
- 切换到你的当前分支:
bashCopy Code
git checkout <current-branch>
- 执行
git cherry-pick
操作:bashCopy Codegit cherry-pick <commit-hash>
- 如果有冲突,解决冲突后继续:
bashCopy Code
git add <resolved-files> git cherry-pick --continue
- 提交合并:
bashCopy Code
git commit -m "Merged specific commit from <target-branch>"
方法三:使用 git merge --no-commit --no-ff
这个方法会将目标分支的更改合并到当前分支,但不会自动提交。你可以在合并后选择哪些文件添加到暂存区并提交。
操作步骤:
- 切换到目标分支:
bashCopy Code
git checkout <target-branch>
- 执行合并操作,但不提交:
bashCopy Code
git merge <current-branch> --no-commit --no-ff
- 选择性地添加和提交文件:
bashCopy Code
git add path/to/file1 path/to/file2 git commit -m "Merged specific files from <target-branch>"
以上方法可以帮助你在 Git 中合并部分文件,而不是整个提交或分支。