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 thediffcommand 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,diffdisplays the differences using the context diff format. To use the unified output format, which is more commonly used, you can add the-uoption. 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-changeoption. 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.txtThis command comparesfile1.txtandfile2.txtand displays the differences between them. - Comparing two files with unified output:
diff -u file1.txt file2.txtThis command comparesfile1.txtandfile2.txtand displays the differences in the unified format. - Comparing two directories:
diff -r dir1/ dir2/This command compares the files indir1anddir2and displays the differences between them. - Comparing two files, ignoring whitespace changes:
diff --ignore-space-change file1.txt file2.txt
This command comparesfile1.txtandfile2.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.