Introduction
In Linux system management and software development, it is common to find the need to modify configuration files, source code or scripts without having to rewrite them completely. The commandpatchallows precise changes to be applied by a different file, known as a patch. This tool is especially valuable when working with software versions, as it facilitates code updating without losing local modifications. In this article we will explore how it workspatchhow to create a patch withdiffand best practices for using it safely and efficiently.
What is the patch command?
The commandpatchread a file containing the differences between two versions of the same file, usually generated with the utilitydiff. These differences are expressed in a standard format that indicates which lines should be added, deleted or modified. When applying the patch,patchseeks to match the context around each change to ensure that the modification is applied in the right place, even if the target file has experienced small variations. If the context doesn't match,patchyou can fail or create a rejection file for the user to manually review.
Creating a diff patch
To generate a patch, you first need to have two versions of the file: the original and the modified. Usingdiff -u original.txt modificada.txt > cambio.patchA patch is produced in a unified format, which is the most legible and widely supported. The option-uincludes several context lines before and after each change, which improves the probability thatpatchapply the patch correctly. Other formats such as-c(classic context) or-e(ed script), also exist but are less used in current practice.
- Basic example:
diff -u archivo_v1.txt archivo_v2.txt > actualizacion.patch - To park several files at once, you can use
diff -urN directorio_v1 directorio_v2 > global.patch - The Flag
-NTreat missing files as empty, avoiding errors when comparing directories.
Applying a patch with patch
Once you have the patch file, applying the change is as simple as runningpatch -p0 < actualizacion.patch. The number after-pindicates how many route components should be removed when looking for the target file;-p0leave the route as it is, while-p1removes the first component (useful when the patch was created from a parent directory). If the patch is applied smoothly,patchwill display a successful message for each processed file.
- Test mode:
patch --dry-run -p0 < actualizacion.patchallows to see what changes will be made without really changing them. - Rejections: When
patchcannot apply a portion, create a file with extension.rejwhich contains the lines that failed. - Reverse a patch: Can be used
patch -R -p0 < actualizacion.patchto undo the changes applied.
Useful Patch Options
In addition to the basic,patchoffers several options that fit your behavior to different scenarios. Knowing them allows you to handle cases where the context does not exactly match or where you want to control the output and the backup files.
-bor--backup: creates a backup of the original file before modifying it, adding a suffix as.origor that specified with--suffix.--verbose: shows detailed information on each step, useful for debugging problems.-d directorio: change to the specified directory before reading the patch, facilitating application from any location.--strip=: equivalent to-p, allows to define how many leading slashes are removed from the patch routes.--binary: treats files as binary data, preventing final line conversions to systems where it matters.
Common problem solution
Althoughpatchis robust, situations may occur where the application fails or results in unexpected results. Knowing to diagnose and correct these problems saves time and avoids introducing errors into the system.
- Non-matching context: occurs when the target file has been modified so that the patch context lines are no longer present. Solution: update the patch using
diffagainst the latest version or reduce the level of context with-C. - White spaces: differences in tabs vs spaces can cause failures. Use
--ignore-whitespaceIt ignores these changes when applying. - Insufficient permissions: if the user does not have permission to write in the target file,
patchHe'll fail. Run withsudoor adjust the permissions before applying. - binary files: apply a text patch to a binary file damages its content. Always check the file type before using
patch.
Good practices and advice
To make the most ofpatchand maintain the integrity of the files, it is recommended to follow certain guidelines that have proved to be effective in production and development environments.
- Always check the patch before applying it: use
catorlessto inspect the content and make sure it only contains the expected changes. - Maintain a version control system (such as Git) along with the use of
patchallows any unwanted modification to be easily reversed. - When multiple files are parked, grouping changes into a single patch facilitates audit and tracking.
- Documenting the reason for each patch in a changelog or in the commit message helps future administrators understand the purpose of the modification.
- Test the patch in a staging environment or a backup before applying it to critical systems.


