Last Updated on November 23, 2023 by Abhishek Sharma
The diff command in Linux stands as a powerful tool for comparing files and directories, offering insights into the differences between them. Whether you’re a seasoned developer, a system administrator, or an enthusiastic Linux user, understanding how to use diff effectively can streamline your workflow and help manage changes within files or directories.
This article aims to provide a comprehensive guide to the diff command, exploring its functionalities through various examples. From basic file comparisons to more advanced options, readers will gain a deeper understanding of how to leverage this versatile tool efficiently.
What is diff Command Linux?
The diff command in Linux is a powerful utility used for comparing files line by line. Here are several examples demonstrating how the diff command can be used:
Example 1: Basic File Comparison
diff file1.txt file2.txt
This command compares the contents of file1.txt and file2.txt, displaying the lines that differ between the two files.
Example 2: Unified Diff Output
diff -u file1.txt file2.txt
Using the -u option, this command generates a unified output that includes context lines and highlights the differences between file1.txt and file2.txt.
Example 3: Ignore White Space Changes
diff -b file1.txt file2.txt
The -b option ignores changes in the amount of white space while comparing file1.txt and file2.txt.
Example 4: Compare Directories Recursively
diff -r directory1 directory2
By using the -r option, this command recursively compares all files in directory1 and directory2, showing the differences between the contents.
Example 5: Creating a Patch File
diff -u original_file modified_file > patch_file.patch
Using the -u option, this command generates a unified diff between original_file and modified_file and saves the differences into a patch file named patch_file.patch.
Example 6: Apply a Patch File
patch original_file patch_file. This generates a unified diff that includes the changes between the original and modified files, saved in the specified patch file.
3. Can diff be used to compare directories?
Yes, diff can compare directories. By using the -r or –recursive option along with diff, you can compare entire directories and identify differences between files within them.
4. Is there a way to ignore white spaces or empty lines during comparison?
Yes, diff offers options like -b (ignore changes in the amount of white space), -B (ignore changes that just insert or delete blank lines), and -w (ignore all white space) to facilitate comparison by ignoring specific types of differences.
5. How can I apply a diff patch to update a file?
To apply a diff patch and update a file, you can use the patch command. For instance, patch original_file patch_file applies the changes specified in the patch file to the original file.