How to Compare Two Files in Bash (With Example)


Often you may want to compare two files in Bash for differences.

There are two common ways to do so:

Method 1: Check if Two Files are the Same

cmp -s teams1.txt teams2.txt && echo "Yes" || echo "No"

This particular example will check if the files named teams1.txt and teams2.txt are the exact same and will return either “Yes” or “No” as a result.

Method 2: Display the Differences Between Two Files

diff teams1.txt teams2.txt

This particular example will return the differences between the files named teams1.txt and teams2.txt.

Here is what the various commands do:

  • cmp: This command stands for “compare” and compares to two files line by line.
  • -s: This command stands for “silent” and tells Bash not to print anything, but simply return an exit status indicating whether the files differ.

The following example shows how to use each of these methods in practice.

Example: How to Compare Two Files in Bash

Suppose that have two files named teams1.txt and teams2.txt that both contain the names of various basketball teams.

We can use the cat command to view the contents of each file:

Suppose that we would first like to check if the two files are exactly the same.

We can use the following syntax to do so:

cmp -s teams1.txt teams2.txt && echo "Yes" || echo "No"

The following screenshot shows how to use this syntax in practice:

Bash compare two files for equality

This returns “No” since the two files are not identical.

To find the differences between the files, we can use the diff command as follows:

diff teams1.txt teams2.txt

The following screenshot shows how to use this syntax in practice:

Bash compare differences between files

Here is how to interpret the output:

The 5, 6c5, 6 tells us that the content in lines 5 and 6 of the first file and the content in lines 5 and 6 of the second file are different.

We can then see that lines 5 and 6 in the first file contain Spurs and Rockets while the lines 5 and 6 in the second file contain Jazz and Nets.

The 9c9 tells us that the content in line 9 of the first file and in line 9 of the second file are different.

We can then see that line 9 in the first file contains Knicks while line 9 in the second file contains Kings.

Note that the three dashes – – – in the output simply separate the content between the first and second files.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Check if File Contains Specific String
Bash: How to Count Number of Unique Lines in File
Bash: How to Check if File is Empty

Leave a Reply