Conflicts
If you are dealing with multiple branches, you can start to run into situations where a change to a file in one branch actually conflicts with changes to a file in another branch. When you merge these two branches together, you will likely get conflicts that need to be fixed before your can finish the merge.
Let’s get back to our sample repository:
cd ~/my_project
And let’s create a “problematic” branch were we will place conflicting changes.
git branch problem
git branch
git checkout problem
Let’s make a change to file1.txt
.
echo 'THIS IS GOING TO BE A PROBLEM!' >> file1.txt
cat file1.txt
Let’s stage and commit this change.
git add file1.txt
git commit -m "Making problems in file1"
Now, let’s switch back to our master
branch and make a change to file1.txt
there.
git checkout master
echo 'I want this change in file1.' >> file1.txt
cat file1.txt
And let’s stage and commit this change.
git add file1.txt
git commit -m "This is an innocent change."
Now, we have 2 changes to the same file, so when we try to merge the problem
branch into master
, Git won’t know which commit to use, or in which order to apply the changes. So, it just fails!
git merge problem -m "Trying to merge my problem."
Now, look at file1.txt
.
cat file1.txt
You can see that the problematic file (file1.txt
) has been marked with the conflicting lines.
Also, look at what the status now is.
git status
This message is basically telling you that you are in the middle of a merge and the “Unmerged paths” are where your conflicts exist. So, let’s fix the conflicts.
In this case, I am going to change file1.txt
to be what I actually want it to be.
echo "This is some text." > file1.txt
echo "" >> file1.txt
echo "And here's some more text." >> file1.txt
echo "" >> file1.txt
echo "I want this change in file1." >> file1.txt
cat file1.txt
And note that the status hasn’t changed!
git status
We have to stage the changes we made and then commit them in order to finish the commit.
git add file1.txt
git commit -m "Fixing conflict in file1"
git status
And we’re done! Look at the commit logs and see what happened.
git log --oneline
All of the changes are there! Even the bad ones, and the fix that made it all work.
Now that we have merged problem
into master
, and fixed all of the changes, let’s delete the problem
branch.
git branch
git branch -d problem