Linux: The diff and patch commands.

As a Linux sysadmin / developer you will need more than once to update files and pass those changes to other users, most likely you will do…

Linux: The diff and patch commands.
Photo by Diana Polekhina on Unsplash

As a Linux sysadmin / developer you will need more than once to update files and pass those changes to other users, most likely you will do this using version control tools like git which is the preferred way, but what if those files are in computers that cannot have connectivity with our version control system? in such rare cases the tools to help you are the diff and the patch commands.

How to use diff and patch

diff is used to compare files and view their differences. We have two files, a.txt and a_fixed.txt

a.txtaaa
bbb
ccc

a_fixed.txtaaa
eee
ccc

To compare those two files enter$ diff -u a.txt a_fixed.txt
--- a.txt       2022-06-18 22:24:25.659116428 +0300
+++ a_fixed.txt 2022-06-18 22:24:35.849116285 +0300
@@ -1,3 +1,3 @@
aaa
-bbb
+eee
ccc

In this example we compare a.txt vs a_fixed.txt , if would like to compare a_fixed.txt vs a.txt have to change the order of files in the diff command$ diff -u a_fixed.txt a.txt
--- a_fixed.txt 2022-06-18 22:24:35.849116285 +0300
+++ a.txt       2022-06-18 22:24:25.659116428 +0300
@@ -1,3 +1,3 @@
aaa
-eee
+bbb
ccc

The minus symbol before the line indicates what is removed in the first file, the plus symbol before the line indicates what is added.

Now lets assume that we are happy with the changes to a_fixed.txt and we want to apply those changes to a.txt in a computer that is not network connected but we can transfer the file via a USB stick. The first thing you have in your mind is just to copy the whole file, which might sound like a good option but really isn't because

  • What if the changes are minimal and the file very large, large in terms of gigabytes or terabytes
  • What if we have done a mistake and actually over-write the wrong file?

One way avoid such mistakes is to create a patch file from the output of diff command$ diff -u a.txt a_fixed.txt > my_fix.patch

The benefits of creating a patch are

  • The patch is probably much smaller than the full file.
  • You have the opportunity to review a much more smaller file before applying the patch to the target file and even the patch might fail in cases that you try to apply the patch to a wrong file

To apply the patch enter$ patch a.txt < my_fix.patch
patching file a.txt

if no errors occurred the file has been patched successfully, i hope you found this article interesting and and make you apply some patches :)