How to Compare and Merge Three Files Using the diff3 Command in Linux

When multiple developers are working on the same source code file simultaneously, conflicts are inevitable. If Developer A changes line 10 on their laptop, and Developer B changes line 10 on their desktop, the version control system must resolve the conflict. While the standard diff command is excellent for comparing two files, resolving complex merge conflicts requires comparing three files: Developer A’s version, Developer B’s version, and the original common ancestor file they both started from. To do this from the Linux command line, you must use the diff3 command.

How the diff3 Command Works

The diff3 command accepts exactly three file arguments. By convention, you should format the command in this specific order: the first modified file (mine), the older common ancestor file (older), and the second modified file (yours).

diff3 my_script.sh common_ancestor.sh your_script.sh

The output of diff3 is significantly more complex than standard diff. It uses numbered blocks (e.g., ====1 or ====3) to indicate which of the three files differs from the others.

  • If file 1 and file 2 are identical, but file 3 is different, diff3 will highlight file 3.
  • If file 1 and file 3 are identical, but file 2 (the ancestor) is different, it means both developers independently made the exact same change.

Automating the Merge (The -m Flag)

Analyzing the raw output of diff3 is incredibly difficult for human readers. Therefore, the command is almost always used with the -m (merge) flag.

When you use the -m flag, diff3 does not just print the differences; it attempts to automatically merge all the changes into a single, cohesive file and prints the final result to the standard output.

diff3 -m my_script.sh common_ancestor.sh your_script.sh > final_merged.sh

If Developer A edited the top of the file, and Developer B edited the bottom of the file, diff3 will successfully merge both changes seamlessly into final_merged.sh.

Handling Unresolvable Conflicts

If both developers edited the exact same line of code in conflicting ways, diff3 cannot automate the merge. It will still output the merged file, but it will aggressively highlight the conflicting section using canonical version control conflict markers (<<<<<<< and >>>>>>>).

<<<<<<< my_script.sh
print("Hello World")
||||||| common_ancestor.sh
print("Hello")
=======
print("Hello Universe")
>>>>>>> your_script.sh

You must then manually open final_merged.sh in a text editor like nano or vim, find these visual markers, delete them, and manually type out the final, correct line of code.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.