patch

Learn how to use the patch command to apply code changes to files and directories. Understand patching, reversing patches, and handling multiple files with this essential developer tool.

Patch Command Guide

The patch command is a powerful utility used in Unix-like operating systems to apply changes to files. These changes are typically generated by the diff command, creating a "patch file" that describes the differences between two versions of a file. This guide explains how to use the patch command for various scenarios.

Applying a Patch to a Single File

To apply a patch to a single file, you redirect the content of the patch file into the patch command. The basic syntax is:

patch <file> < <patch-file>

Here, <file> is the target file you want to modify, and <patch-file> is the file containing the patch instructions.

Reversing a Patch

If you need to undo the changes made by a patch, you can use the -R option. This tells patch to apply the reverse of the changes described in the patch file.

patch -R <file> < <patch-file>

This is useful for reverting specific modifications without having to manually edit the file.

Patching Files in a Directory

The patch command is also effective for applying changes to multiple files within a directory, especially when dealing with source code repositories. The -p option is crucial here, as it strips a specified number of leading path components from the filenames found in the patch file.

To patch all files in a directory, adding any missing new files, and stripping one level of directory prefix (common when patches are generated from a subdirectory):

cd dir
patch -p1 -i <patch-file>

In this command:

  • cd dir: Navigates you into the directory where the files to be patched reside.
  • -p1: Strips one leading directory component from the file paths in the patch file. For example, if the patch file refers to a/src/file.c, -p1 will cause patch to look for src/file.c in the current directory.
  • -i <patch-file>: Specifies the input patch file.

Patching with Offset

Sometimes, the directory structure where you are applying the patch differs slightly from the structure where the patch was created. The -p option allows you to specify an offset.

To patch files in a directory, with one level (/) offset:

patch -p1 -r <dir> < <patch-file>

Note: The use of -r <dir> in this context is less common for standard patching and might be intended for specific scenarios or custom scripts. Typically, -p1 is used to adjust path offsets. For standard directory patching, -p1 -i <patch-file> is more conventional.

Further Resources