OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

patch

The patch program is used to apply changes to text files. It accepts output from diff and is generally used to convert older version of files into newer versions. Let’s consider a famous example. The Linux kernel is developed by a large, loosely organized team of


contributors who submit a constant stream of small changes to the source code. The Linux kernel consists of several million lines of code, while the changes that are made by one contributor at one time are quite small. It makes no sense for a contributor to send each developer an entire kernel source tree each time a small change is made. Instead, a diff file is submitted. The diff file contains the change from the previous version of the kernel to the new version with the contributor's changes. The receiver then uses the patch program to apply the change to his own source tree. Using diff/patch offers two significant advantages:

1. The diff file is very small, compared to the full size of the source tree.

2. The diff file concisely shows the change being made, allowing reviewers of the patch to quickly evaluate it.

Of course, diff/patch will work on any text file, not just source code. It would be equally applicable to configuration files or any other text.

To prepare a diff file for use with patch, the GNU documentation (see Further Reading below) suggests using diff as follows:

diff -Naur old_file new_file > diff_file

Where old_file and new_file are either single files or directories containing files. The r

option supports recursion of a directory tree.

Once the diff file has been created, we can apply it to patch the old file into the new file:

patch < diff_file

We’ll demonstrate with our test file:



[me@linuxbox ~]$ diff -Naur file1.txt file2.txt > patchfile.txt

[me@linuxbox ~]$ patch < patchfile.txt

patching file file1.txt [me@linuxbox ~]$ cat file1.txt b

c d e

[me@linuxbox ~]$ diff -Naur file1.txt file2.txt > patchfile.txt

[me@linuxbox ~]$ patch < patchfile.txt

patching file file1.txt [me@linuxbox ~]$ cat file1.txt b

c d e


In this example, we created a diff file named patchfile.txt and then used the patch program to apply the patch. Note that we did not have to specify a target file to patch, as the diff file (in unified format) already contains the filenames in the header. Once the patch is applied, we can see that file1.txt now matches file2.txt.

patch has a large number of options, and there are additional utility programs that can be used to analyze and edit patches.


Top OS Cloud Computing at OnWorks: