patch
patch
The patch
command applies a diff file (usually generated by the diff
command) to one or more original files, resulting in a patched version of those files.
Basic Syntax
original-file
: The file(s) to which the patch should be applied.patchfile
: The file containing the patch to be applied.
Key Options
-pNUM, --strip=NUM
: Strip the smallest prefix containing NUM leading slashes from filenames found in the patch file. This is useful when the paths in the patch file do not match exactly with the paths in your current directory structure.-i PATCHFILE, --input=PATCHFILE
: Specifies the patch file to use.-R, --reverse
: Reverses the patch, i.e., removes the changes applied by the patch from the original file(s).-o OUTFILE, --output=OUTFILE
: Specifies an output file for rejected hunks (parts of the patch that could not be applied cleanly).-b, --backup
: Make a backup before applying the patch.
Examples
Applying a Patch
Apply a patch to a file:
Specifying Patch File
Specify the patch file to use:
Reverse Patch
Reverse a patch (unapply changes):
Handling Rejected Patches
Save rejected hunks to a file:
Strip Leading Directory
Strip the leading directory from filenames in the patch file:
Explanation with Examples
Applying a Patch
Applying a patch to a file involves using the
-i
option followed by the patch file and specifying the original file:This command applies the changes specified in
patchfile.txt
tooriginalfile.txt
.Specifying a Patch File
If you have a patch file named
mypatch.diff
, you can apply it directly:This command applies the changes specified in
mypatch.diff
to the corresponding files.Reversing a Patch
To reverse or undo a patch, you use the
-R
option:This command removes the changes applied by
mypatch.diff
from the original files.Handling Rejected Patches
When a patch cannot be applied cleanly (due to conflicts), you can save the rejected parts to a file using the
-o
option:This command saves the rejected hunks (parts of the patch that couldn't be applied) to
rejected.txt
.Stripping Leading Directory
If your patch file contains paths with a different structure than your current directory, you can strip the leading directory component using the
-p
option:This tells
patch
to ignore the first directory component in the paths specified inmypatch.diff
.
Usage in Scripts and Automation
The patch
command is often used in scripts and automated processes, especially in software development and system administration tasks where applying patches to files and directories is necessary for updates and fixes.
Conclusion
The patch
command is essential for managing changes to files and directories in a controlled and reversible manner. It allows you to apply, reverse, and manage patches efficiently, making it a powerful tool for maintaining software and system configurations.
help
Last updated