patch Command: Tutorial & Examples

Apply a diff file to an original file

The patch command is used to apply a diff file to an original file, in order to update or modify the original file. A diff file contains the differences between the original file and a modified version of that file, and the patch command uses this information to update the original file.

The basic syntax for using the patch command is as follows:

patch [options] original_file.txt patch_file.diff

Here are a few examples of how the patch command can be used:

  • Apply a patch to a file:

    patch -p1 < mypatch.diff

  • Apply a patch in reverse

    patch -R -p1 < mypatch.diff

  • Dry run a patch file

    patch --dry-run -p1 < mypatch.diff

In the first example, the -p1 option is used to strip the leading pathname component, and the patch file is passed to the command as standard input. In the second example, the -R option is used to apply the patch in reverse, so it undoes any changes made by the patch. In the third example, the --dry-run option is used to check what changes the patch will make, but it will not make any changes to the file.

It's important to note that the patch file needs to be created with the diff command in order to be able to be used with the patch command. The patch file contains the difference between the original file and the new version of the file.

Except where otherwise noted, content on this site is licensed under a CC BY-SA 4.0 license CC BY SA