diff Command Examples in Linux

The diff command is used to compare text files. The command displays the two files and the differences between them. Using various symbols, the output suggests how you can change one file to make it identical to the other. Each symbol has a special meaning.

The less than symbol () with a line after it means that line should be added from the second file. In addition, the diff command also denotes the line numbers for each file that would be affected by deletion, addition, and change operations.

Syntax

The syntax of the diff command is:

# diff {file name 1} {file name 2}

diff COMMAND OPTIONS

The diff command has various options that enable you to specify the nature of the output.

Option Description
-b Ignore spacing differences.
-i Ignore case differences.
-t Expand tab characters in output lines.
-w Ignore spacing differences and tabs.
-c Display a list of differences with three lines of context.
-u Output results in unified mode, which presents a more streamlined format.

diff Command Examples

1. Compare files (lists changes to turn `old_file` into `new_file`):

# diff old_file new_file

2. Compare files, ignoring white spaces:

# diff --ignore-all-space old_file new_file

3. Compare files, showing the differences side by side:

# diff --side-by-side old_file new_file

4. Compare files, showing the differences in unified format (as used by `git diff`):

# diff --unified old_file new_file

5. Compare directories recursively (shows names for differing files/directories as well as changes made to files):

# diff --recursive old_directory new_directory

6. Compare directories, only showing the names of files that differ:

# diff --recursive --brief old_directory new_directory

7. Create a patch file for Git from the differences of two text files, treating nonexistent files as empty:

# diff --text --unified --new-file old_file new_file > diff.patch

8. diff can also compare directories:

# diff dir1 dir2

which compares any same-named files in those directories, and lists all files that appear in one directory but not the other. To compare entire directory hierarchies recursively, use the -r option:

# diff -r dir1 dir2

which produces a (potentially massive) report of all differences.

Conclusion

The diff command compares two files line-by-line, or two directories. When comparing text files, diff can produce detailed reports of their differences. For binary files, diff merely reports whether they differ or not. For all files, if there are no differences, diff produces no output.

Related Post