git實戰8 – 當有2個分支且都各自commit過後,但2個分支都修改到相同一個檔案的同一行產生衝突時


建立目錄

mkdir git_test_2
cd git_test_2

建立倉庫

git init
Initialized empty Git repository in /home/ben/git_test_2/.git/

建立檔案 1.txt,內容為0

echo 0 > 1.txt
git add .
git commit -m 'master 1'
[master (root-commit) f105c67] master 1
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 1.txt

建立分支 addfun 並 checkout 到 addfun 中

git checkout -b addfun
Switched to a new branch 'addfun'

在 addfun 中建立檔案 2.txt

echo 2 > 2.txt

修改檔案 1.txt,注意!此時更動到原本 1.txt 的舊行數

echo 1 > 1.txt
git add .
git commit -m 'addfun 1'
[addfun e901246] addfun 1
2 files changed, 2 insertions(+), 1 deletions(-)
create mode 100644 2.txt

回到 master

git checkout master
Switched to branch 'master'
[ben@ben git_test_2]$ ll
total 4
-rw-rw-r-- 1 ben ben 2 Jul  3 15:13 1.txt

此時 master 的 1.txt 仍為 0

cat 1.txt
0

重新修改 1.txt 的內容,原本的第1行改為 00

echo '00' > 1.txt
git add .
git commit -m 'master 2'
[master 150ae6b] master 2
1 files changed, 1 insertions(+), 1 deletions(-)
git status
# On branch master
nothing to commit (working directory clean)

在 master 中合併 addfun,會發現衝突產生了

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

查看目前狀態,git 有合併,但沒有 commit,需要我們手動處理衝突再 commit

git status
# On branch master
# Changes to be committed:
#
#       new file:   2.txt
#
# Unmerged paths:
#   (use "git add/rm <file>..." as appropriate to mark resolution)
#
#       both modified:      1.txt
#
ll
total 8
-rw-rw-r-- 1 ben ben 41 Jul  3 15:14 1.txt
-rw-rw-r-- 1 ben ben  2 Jul  3 15:14 2.txt

查看 1.txt 的內容 ===== 上面為 master 的內容 ===== 下面為 addfun 的內容

cat 1.txt
<<<<<<< HEAD
00
=======
1
>>>>>>> addfun

此步驟為解決衝突
修改 master 的 1.txt 內容,再手動 commit

echo 1 > 1.txt
git add .
git commit -m 'master 3'
[master a31b833] master 3
git status
# On branch master
nothing to commit (working directory clean)
ll
total 8
-rw-rw-r-- 1 ben ben 2 Jul  3 15:14 1.txt
-rw-rw-r-- 1 ben ben 2 Jul  3 15:14 2.txt

查看 log

git log
commit a31b833112c19be702ee3f054efcffd000bb3211
Merge: 150ae6b e901246
Author: Wen-i Hsu <hsu.weni@gmail.com>
Date:   Thu Jul 3 15:15:00 2014 +0800

    master 3

commit 150ae6ba518919b9440343cbc5ddb9761966a8df
Author: Wen-i Hsu <hsu.weni@gmail.com>
Date:   Thu Jul 3 15:13:56 2014 +0800

    master 2

commit e90124603e124842c554b03c00443151b3bf88fe
Author: Wen-i Hsu <hsu.weni@gmail.com>
Date:   Thu Jul 3 15:13:25 2014 +0800

    addfun 1

commit f105c67e126dbd9ac884316dc5e1abfcf91227e1
Author: Wen-i Hsu <hsu.weni@gmail.com>
Date:   Thu Jul 3 15:12:36 2014 +0800

    master 1