Skip to main content
  1. Learn
  2. Software Development
  3. Guides
  4. Git tutorial
  5. 如何使用 Git
  6. 如何在 Git 中使用分支
  7. 解決合併的衝突
GuidesSoftware DevelopmentBacklog
Git

Project and code management together.

解決合併的衝突

接下來,讓我們把我們在上個步驟建立的issue2issue3分支,合併到主分支。

首先,切換到main,並使用快轉合併,來合併issue2

$ git checkout main
Switched to branch 'main'
$ git merge issue2
Updating b2b23c4..8f7aa27
Fast-forward
myfile.txt |    2 ++
  1 files changed, 2 insertions(+), 0 deletions(-)

現在的歷史紀錄如下:

Current history

接下來,嘗試將issue3合併到main中。

$ git merge issue3
Auto-merging myfile.txt
CONFLICT (content): Merge conflict in myfile.txt
Automatic merge failed; fix conflicts and then commit the result.

在這種情況下,Git 已識別出衝突,因為myfile.txt檔案在每個分支上的同一行中具有不同的內容,並且無法自動將issue3main合併。

myfile.txt檔案現在看起來像這樣:

Anyone can learn Git with this tutorial and Backlog
add: Register a change in an index
<<<<<<< HEAD
commit: Save the status of an index
=======
pull: Obtain the content of a remote repository
>>>>>>> issue3

您會發現 Git 新增到myfile.txt檔案的標記,以及有關衝突的資訊。我們必須手動修復衝突,如下所示。

Anyone can learn Git with this tutorial and Backlog
add: Register a change in an index
commit: Save the status of an index
pull: Obtain the content of a remote repository

解決衝突後,提交更改。

$ git add myfile.txt
$ git commit -m "merge issue3 branch"
# On branch main
nothing to commit (working directory clean)

歷史紀錄將如下所示:

Current history

您可以看到,由於衝突的解決,一個新的合併提交已經被創建。主分支現在指向最新的合併提交。這是一個非快轉合併。

Subscribe to our newsletter

Learn with Nulab to bring your best ideas to life