Linux diff command and Practical example on how to use it

The diff command in Linux is used to compare the contents of two files or directories and display the differences between them. It is often used to find changes between different versions of files or to compare directories for discrepancies.

Here’s an overview of how to use the diff command:

  1. Comparing Two Files:
    To compare two files, use the diff command followed by the names of the two files. For example:
   diff file1.txt file2.txt

This command compares file1.txt and file2.txt and displays the differences between them.

  1. Unified Output Format:
    By default, diff displays the differences using the context diff format. To use the unified output format, which is more commonly used, you can add the -u option. For example:
   diff -u file1.txt file2.txt

This command compares file1.txt and file2.txt and displays the differences in the unified format.

  1. Comparing Directories:
    To compare two directories and find differences between their files, use the -r (recursive) option. For example:
   diff -r dir1/ dir2/

This command recursively compares the files in dir1 and dir2 and displays the differences between them.

  1. Ignoring Whitespace:
    Whitespace differences, such as spaces and tabs, can sometimes be irrelevant. To ignore whitespace differences during the comparison, you can use the --ignore-space-change option. For example:
   diff --ignore-space-change file1.txt file2.txt

This command compares file1.txt and file2.txt, ignoring whitespace changes.

  1. Examples:
  • Comparing two files: diff file1.txt file2.txt This command compares file1.txt and file2.txt and displays the differences between them.
  • Comparing two files with unified output: diff -u file1.txt file2.txt This command compares file1.txt and file2.txt and displays the differences in the unified format.
  • Comparing two directories: diff -r dir1/ dir2/ This command compares the files in dir1 and dir2 and displays the differences between them.
  • Comparing two files, ignoring whitespace changes:
    diff --ignore-space-change file1.txt file2.txt
    This command compares file1.txt and file2.txt, ignoring whitespace differences.

The diff command provides a convenient way to compare files and directories, allowing you to identify differences between them. It is useful for verifying changes in files, finding discrepancies between versions, and ensuring the accuracy of file transfers or backups.

For more information about the diff command and its options, you can refer to the manual page by typing man diff in your terminal.