Linux Training : 13. diff and patch

diff and patch

In order to make modification to existing files easy, the commands diff and patch were created. diff finds differences and patch will take a patch file and add it to an existing file.
When comparing two files in the same directory, the output from diff will not have any path preceding the filenames involved. If, however, the new file is in a separate directory from the old file, the patch file will have path data prepended to the new file name. This makes for some confusion when running patch.
patch has a flag, -p, that is used to indicate how many levels of path data to strip from the filename in order to align the patch with the original source file. If the new source is in the same directory, use -p0. If it's up one directory, use -p1. Up two, use -p2.

  • common diff uses

    • diff -u <source1> <source2>
      • This will find the additional and missing lines in source2 as compared to source1 and use the unified output format. This is the most common way to use diff when generating a patch file.
    • diff --side-by-side <source1> <source2> or diff -y <source1> <source2>
      • The screen will be split and the two files will be shown line by line with additions and subtractions shown fairly clearly.

Finding what changed on a system is such a common operation that many variants of diff have been formed to do a similar process in different formats or environments.
See locate diff | grep "/usr/bin" for a list on your system.

  • patch use

    • patch -p# <patchfile
      • This form is pretty much the only form used. When patch fails you see messages like "hunk 3 failed". So hunks 1 and 2 succeeded but 3 has a problem. A hunk is a patch section of an addition or deletion.

Since the exercise below requires editing a file, it may be required to review the section on vi first.

diff and patch exercise

Create a file, file1, that has some text cut from a web page.
Copy that file to a new file, file2 up one directory level, and edit the new file. Make some word changes and add and delete some lines.
Now use diff and make a patch file called patch1.
Copy file1 again to be file3 and apply the patch1.
Lastly run diff to verify that file2 and file3 are the same.