diff

From LinuxReviews
Jump to navigationJump to search

diff is a small command-line tool that lets you compare the difference between two text files. It can output the difference formatted as a patch which can later be used to patch the original file so it becomes the changed one.

The Basics[edit]

Running diff oldfile newfile is enough to see the differences between two files but the output is not very useful. It is more useful with the -u for --unified option which displays the differences and, by default, three lines of context around the changes between the two files compared.

diff -u oldfile newfile

The git source management system will use diff -u when you git makepatch. Many programmers expect that a diff between two C or C++ files is made using diff -u. It is also what the patch program for patching files against a .diff file expects.

You can use number like 8 and the long variant of the -u option as in diff --unified=8 oldfile newfile to get more context around the changes (-u=8 does not work):

diff --unified=8 oldfile newfile

The three line default is typically more than enough.

White spaces may be irrelevant to the changes you want to highlight when you compare two files. The -w option can be used to ignore whitespaces:

diff -w oldfile newfile

Side By Side Comparsion[edit]

diff -y will show the differences between two files side by side with the original file on the left and the changed file on the right:

diff -y oldfile newfile

Note that the diff -y formatting style can not be combined with other styles like diff -u. You can combine -y with -w to ignore whitespaces.

Comparing Directories[edit]

diff can be used to compare directories recursively with the -r option. This mode makes it show any differing files/folders and the changes between the files in those folders. This is useful if you have two almost identical folders like original_source and my_source_tree_branch that were based on the same tarball or tree:

diff -r original_source/ my_source_tree_branch/

The same recursive mode can be used to only show the names of the files that are different by adding -q (for --brief, not --quiet):

diff -rq original_source/ my_source_tree_branch/

Links[edit]


Add your comment
LinuxReviews welcomes all comments. If you do not want to be anonymous, register or log in. It is free.