How to Generate and Apply Patches using diff and patch on Linux

Posted on In Linux, Programming

`diff` and `patch` are tools to create patches and apply patches to source code, which is widely used in the open-source world, such as Linux kernel and application.

patch: applying patches

To apply a patch to a single file:

$ patch < foo.patch

If the foo.patch does not identify the file the patch should be applied to, you can specify the file:

$ patch foo.txt < bar.patch

Applying patches to a directory:

$ patch -p1 < bar.patch

Here, we set a "p level". The p level specifies the parts of the path name to ignore by path.

For example, the bar.patch applies patches to:

/home/eric/package/src/mm/mm.c

To apply the patches correctly in directory src:

$ patch -p3 < bar.patch

To remove a patch:

$ patch -p5 -R < bar.patch

diff: creating patches

To create a patch for a single file:

$ diff -u original.c new.c > patch-to-file.patch

To create a patch for a source tree:

$ diff -rupN original/ new/ > patch-to-dir.patch

Here, original is the original source tree and new is the new source tree that you have changed.

More about diff and patch

Read the man pages for more information about `diff` and `patch`:

[[man:1p|diff|diff man pages]].

[[man:1p|patch|patch man pages]].

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *