Introduction
This tutorial provides an introduction to the patch
command in Linux, a utility used to apply changes to text files using patch files. Patch files contain differences between the original file and a modified version.
This tutorial provides an introduction to the patch
command in Linux, a utility used to apply changes to text files using patch files. Patch files contain differences between the original file and a modified version.
The patch
command is a powerful tool for applying changes to files based on information provided in a patch file. It is commonly used for distributing and applying updates to source code.
Let's begin by understanding the basic usage of the patch
command. The patch
command is used to apply changes to a file using information from a patch file. We can use the cat
command to view the contents of the patch file, and the cd
command to navigate to the directory containing the original and modified files.
Input:
cd /home/labex/project
cat original_file
patch -p0 < patchfile.patch
cat original_file
Output:
Hello, World!
How are you?
I'm fine.
patching file original_file
Hunk #1 succeeded at 1 with fuzz 1.
Hello, OpenAI!
How are you?
I'm doing great.
In this example, the patch
command applies changes from the changes.patch
file to the original_file.txt
.
The patch
command provides options to customize the application of patches and handle various scenarios.
patch [options] patch-file
-R
: Canceled patches.This example showcases the diff -Naur
command, a powerful tool for generating a unified diff between two files. The -Naur
options instruct diff to treat absent files as empty and produce a unified diff in a human-readable format. The resulting patchdiff.txt
file captures the differences between the files, facilitating easy identification and application of changes using the patch command.
Input:
cat file1.txt
diff -Naur file1.txt file2.txt > patchdiff.txt
patch < patchdiff.txt
cat file1.txt
Output:
a
b
c
12
patching file file1.txt
b
c
e
10
In this example, the -R
option in the patch command is utilized to revert the changes applied in the previous example. The command patch -R < patchdiff.txt
effectively rolls back the modifications made by the previous patch, restoring the original state of the file. The -R
option stands for "reverse" and is essential for undoing previous patch applications.
Input:
patch -R < patchdiff.txt
cat file1.txt
Output:
patching file file1.txt
a
b
c
12
The patch
command is a valuable tool for applying changes to text files using patch files. Whether you need to preview changes, strip leading components from file names, or reverse patches, the patch
command provides flexibility for managing updates and modifications to files.