How to compare 2 files using ‘diff’ in Linux

This article will introduce you to the diff command on Linux which is used to compare two files and display the “differences” between the two. I will also provide you with a Bash shell script to compare two files and simply output if they are the same or not. Lets begin with the basic usage of diff

Using Diff to Compare 2 Files

diff filename1 filename2

Simply provide the two files you want to compare to the diff utility and the resulting output will be a list of differences between the two files. If the two files are exactly the same, the output will be blank.

There are some useful parameters that can be passed into diff that you might like to use:

-b Ignore differences in whitespace (For example: If the beginning of line 1 has 1 space in file1, and 2 spaces in file2, this difference will be ignored.

-B Ignore additional or missing blank lines. This works similar to the previous options but applies to lines instead of spaces

Example Bash Script

#!/bin/sh
if diff $1 $2 >/dev/null ; then
echo Files are Same
else
echo Files are Different
fi

This bash script will compare two files that you specify as parameters and simply output if they are the same or not. In some cases, you do not need to know the details of the differences but just whether they are different or not and this script does just that. Simply save this script into your system (lets call it heatware_diff.sh) and run it with the following syntax:

See also  How to List All Installed RPM Packages in Linux

heatware_diff.sh filename1 filename2

Leave a Comment