【嵌入式开发 Linux 常用命令系列 8 -- git checkout 解冲突详细介绍】

文章目录

  • [1. Git 冲突产生的场景](#1. Git 冲突产生的场景)
  • [2. 冲突标记符号解释](#2. 冲突标记符号解释)
  • [3. git checkout --ours 和 git checkout --theirs](#3. git checkout --ours 和 git checkout --theirs)
  • [4. 操作完成后的流程](#4. 操作完成后的流程)
  • [5. 举例演示](#5. 举例演示)

1. Git 冲突产生的场景

当你在 git mergegit rebasegit cherry-pick 等操作时,如果 同一个文件的同一部分在两个分支中都被修改了,Git 就会无法自动合并,结果是产生冲突。

冲突后的文件中会出现类似这样的标记:

diff 复制代码
<<<<<<< HEAD
printf("Hello from main branch\n");
=======
printf("Hello from feature branch\n");
>>>>>>> feature

2. 冲突标记符号解释

  • <<<<<<< HEAD

    表示 当前分支(即你所在的分支) 的内容,也就是 ours

  • =======

    表示 ours 与 theirs 的分隔符。

  • >>>>>>> feature

    表示 要合并进来的分支(目标分支) 的内容,也就是 theirs

所以:

  • ours = 当前分支(HEAD)

  • theirs = 你要合并的分支

3. git checkout --ours 和 git checkout --theirs

这两个命令在冲突文件存在时使用,可以帮助你快速选择保留哪一方的版本。

语法

bash 复制代码
git checkout --ours <file>
git checkout --theirs <file>

含义

  • git checkout --ours <file>

    <file> 冲突部分全部替换为 当前分支(HEAD,ours) 的内容。

  • git checkout --theirs <file>

    <file> 冲突部分全部替换为 合并进来的分支(theirs) 的内容。

使用场景

  1. 如果你 确信本地分支的修改更正确,执行:

    bash 复制代码
    git checkout --ours filename.c
  2. 如果你 确信远端分支的修改更正确,执行:

    bash 复制代码
    git checkout --theirs filename.c
  3. 如果想要手动融合两边的修改(而不是简单选择一方),就要编辑冲突文件,把冲突标记符号 <<<<<<<=======>>>>>>> 删除,并保留你想要的代码。

4. 操作完成后的流程

无论是用 --ours--theirs,还是手动修改,最后都要:

bash 复制代码
git add <file>
git commit

Git 会生成一个合并提交(如果是 merge)。

5. 举例演示

假设我们在 main 分支有:

c 复制代码
printf("Hello from main branch\n");

feature 分支有:

c 复制代码
printf("Hello from feature branch\n");

合并时冲突文件会是:

diff 复制代码
<<<<<<< HEAD
printf("Hello from main branch\n");
=======
printf("Hello from feature branch\n");
>>>>>>> feature
  • 如果执行 git checkout --ours file.c → 文件变成:

    c 复制代码
    printf("Hello from main branch\n");
  • 如果执行 git checkout --theirs file.c → 文件变成:

    c 复制代码
    printf("Hello from feature branch\n");

总结:

  • ours = 当前分支 (HEAD)

  • theirs = 要合并进来的分支

  • <<<<<<< / ======= / >>>>>>> 是冲突标记,标记 ours 与 theirs 的不同部分。

  • git checkout --ours → 保留当前分支的修改

  • git checkout --theirs → 保留合并分支的修改