Conflict management#

While git is very good at merging, if two different branches modify the same file in the same location, it simply can’t decide which change should prevail. At that point, human intervention is necessary to make the decision. Git will help you by marking the location in the file that has a problem, but it’s up to you to resolve the conflict. Let’s see how that works by intentionally creating a conflict.

We start by creating a branch and making a change to our experiment file:

git switch -c trouble
echo "This is going to be a problem..." >> experiment.txt
git commit -a -m"Changes in the trouble branch"

And now we go back to the master branch, where we change the same file:

git switch main
echo "More work on the master branch..." >> experiment.txt
git commit -a -m"Mainline work"

So now let’s see what happens if we try to merge the trouble branch into master:

git merge trouble

Let’s see what git has put into our file:

cat experiment.txt

At this point, we go into the file with a text editor, decide which changes to keep, and make a new commit that records our decision. I’ve now made the edits, in this case I decided that both pieces of text were useful, but integrated them with some changes. After, this we make our new commit

git commit -a -m"Completed merge of trouble, fixing conflicts along the way"
git slog

Note

While it’s a good idea to understand the basics of fixing merge conflicts by hand, in some cases you may find the use of an automated tool useful. Git supports multiple merge tools: a merge tool is a piece of software that conforms to a basic interface and knows how to merge two files into a new one. Since these are typically graphical tools, there are various to choose from for the different operating systems, and as long as they obey a basic command structure, git can work with any of them.