The “diff” is abbreviated as “differences” and is used to compare the content of two files and list the changes in standard output.
A set of source codes makes up a piece of software. Developers build the source code that evolves over time. Getting a new file for each update is unrealistic or time-consuming. Therefore, the safest method is to distribute improvements only. The modifications are made to the old file, and then a new or patched file is created for the new software version.
This guide shows you how to use the “diff” command to generate a patch file and then apply it with the “patch” command.
Syntax:
The syntax of the “patch” command is as follows:
$ patch -pnum <patchfile>
Creating a Patch File Using “diff”:
Source Code File 1:
Firstly, two different versions of a source code are required to create a patch file. The source code file I have created is named as “myfile.c”:s
Source Code File 2:
Now, copy the content of myfile.c in the new_myfile.c, using:
Make some changes in the newly-created file:
Checking Difference:
Let’s create a patch file named as myfile.patch:
You can print the patch file by executing the command below:
Applying the Patch File:
To apply patch, use:
Ensure that the patch file is in the directory where the source code file is placed.
Take a Backup Before Applying Patch:
Use “-b” option to build a backup of the patch file:
Setting Backup File Version
If you need multiple backups of a single backup file, then use the “-V” option. It sets the version number of each backup file. Execute the command given below:
Validate Patch Files
If you want to verify or observe the outcome of patching, then use “–dry-run” option. It does not make any modification to the original file:
Reverse/Undo a Patch
The “-R” option is used to reverse or undo a patch that has already been applied.
$ ls –l myfile.c
$ patch –R < myfile.patch
$ ls –l myfile.c
Conclusion:
In Linux operating system, “patch” is a command that allows us to apply patch files to the source codes or configuration files. The patch file is used for software updating purposes. The difference between the original and new files is held in patch files and the “diff” command is used to get the difference or patch. We discussed the usage of the “diff” and the “patch” commands with a number of options such as making backups, dry-running, and reversing the applied patch.