22.合并冲突

在 Git 中,当尝试将两个不同的分支合并时,可能会出现合并冲突。这通常发生在两个分支上都更改了同一文件的同一部分时。

实验

制造冲突

# 切换到新分支
git checkout lgnew

# 编辑test文件,添加一行内容 123,并提交
cat .\lab\test.txt
abc
123
git commit -a -m "added 123 to the test.txt"

# 切换回主分支
git checkout master

# 编辑test文件,添加一行内容 456,并提交
# 编辑test文件,添加一行内容 123,并提交
cat .\lab\test.txt
abc
456
git commit -a -m "added 456 to the test.txt"

# 合并
git merge lgnew
Auto-merging lab/test.txt
CONFLICT (content): Merge conflict in lab/test.txt
Automatic merge failed; fix conflicts and then commit the result.

合并冲突

合并冲突需要手动解决,因为我之前设置了 VScode 为默认编辑器,当冲突出现的时候会自动调用。 ![[22-1.png]]

VScode 把冲突内容非常直观的列举出来了, 现在我们只需更改 Result 部分,并点击 Complete Merge (解决冲突)。然后还需要再次提交,才算完成合并。

$ git commit -m "Resolved merge conflict"

$ git hist
*   64e4a16 2023-05-05 | Resolved merge conflict (HEAD -> master) [aku]
|\
| * 25f40b0 2023-05-05 | added 123 to the test.txt (lgnew) [aku]
* | ea38cf4 2023-05-05 | added 456 to the test.txt [aku]
* | edee6c9 2023-05-05 | Revert "Merge branch 'lgnew'" [aku]
* | 22c6905 2023-05-05 | Merge branch 'lgnew' [aku]

Last updated