Git常见问题-如何解决冲突

2024/04/21 | 字数739 | 阅读2分钟


场景

在Git操作中,冲突一般出现在执行git merge或者git rebase操作后,出现冲突的原因一般是两个人修改了同一文件的同一区域,Git无法判断以哪个修改为准,或者两个都要,或者两个都不要。这就需要程序员手动修复。一般出现冲突后,你看到的提示信息会是这样的:

bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
git rebase
Auto-merging src/a.c
CONFLICT (content): Merge conflict in src/a.c
error: could not apply e06ba3a... print world
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
Recorded preimage for 'src/a.c'
Could not apply e06ba3a... print world

git status -s
UU src/a.c

通过git status -s我们可以看到所有的冲突文件,在输出开头的UU表示unmerged, both modified

打开文件后,我们可以看到对应的差异:

c
1
2
3
4
5
6
7
8
9
#include <stdio.h>
int main(int argc, char *argv[]) {
<<<<<<< HEAD
  printf("hello\n");
=======
  printf("world");
>>>>>>> e06ba3a (print world)
  return 0;
}

手动修复

上面被<<<<<<< HEAD=======包围的部分是你的修改,被=======>>>>>>> e06ba3a (print world)包围的部分是其他人的修改。如果我们需要两个都保留,可以修改为如下所示:

c
1
2
3
4
5
6
#include <stdio.h>
int main(int argc, char *argv[]) {
  printf("hello\n");
  printf("world");
  return 0;
}

注意要去掉git在rebase时生成的提示符信息:<<<<<<<, =======, >>>>>>>,修改完成后,继续执行rebase:

bash
1
2
git add src/a.c
git rebase --continue

如果你有多个提交,上面的修复过程可能会出现多次,直到成功为止。

上一篇:Git常见问题-推送被拒怎么办? 下一篇:Git常见问题-如何回退远端库的代码

【文章不错,鼓励一下】