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:
- Comparing Two Files:
To compare two files, use thediff
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.
- 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.
- 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.
- 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.
- Examples:
- Comparing two files:
diff file1.txt file2.txt
This command comparesfile1.txt
andfile2.txt
and displays the differences between them. - Comparing two files with unified output:
diff -u file1.txt file2.txt
This command comparesfile1.txt
andfile2.txt
and displays the differences in the unified format. - Comparing two directories:
diff -r dir1/ dir2/
This command compares the files indir1
anddir2
and displays the differences between them. - Comparing two files, ignoring whitespace changes:
diff --ignore-space-change file1.txt file2.txt
This command comparesfile1.txt
andfile2.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.