Monday, March 17, 2025

How to Use the patch Command in Linux

 The patch command in Linux is a powerful tool used to apply changes to files based on differences (diffs) between file versions. It's commonly used in software development to update source code files. In this blog post, we'll explore how to use the patch command with practical examples.

Understanding the patch Command

The patch command takes a patch file (which contains differences between files) and applies those changes to the original file. The patch file is usually created using the diff command.

Basic Syntax

patch [options] [originalfile] [patchfile]
  • originalfile: The file to be patched.
  • patchfile: The file containing the differences.

Creating a Patch File

Before we can use the patch command, we need a patch file. Let's create one using the diff command.

Example: Creating a Patch File

Suppose we have two files, file1.txt and file2.txt, and we want to create a patch file that contains the differences between them.

diff -u file1.txt file2.txt > changes.patch

This command generates a unified diff and saves it to changes.patch.

Applying a Patch

Now that we have our patch file, let's apply it using the patch command.

Example: Applying a Patch

patch file1.txt < changes.patch

This command applies the changes from changes.patch to file1.txt.

Common Options

The patch command has several options that can be useful:

  • -pNUM: Strip NUM leading components from file names.
  • -R: Reverse the patch (undo changes).
  • --dry-run: Test the patch without applying changes.

Example: Using Options

patch -p1 file1.txt < changes.patch

This command strips one leading component from file names before applying the patch.

Handling Rejected Patches

Sometimes, patches may not apply cleanly, resulting in rejected patches. These are saved in .rej files.

Example: Handling Rejected Patches

patch file1.txt < changes.patch

If there are rejected patches, they will be saved in file1.txt.rej. You can manually review and apply these changes.

No comments: