Diff apply patch linux

Linux diff – How to Compare Two Files and Apply Changes with the Patch Command

Zaira Hira

Zaira Hira

Linux diff – How to Compare Two Files and Apply Changes with the Patch Command

Imagine waking up one day to find out that your production systems are down because of a bug that has yet to be traced. One of your worst nightmares right?

And you also discover that you need to compare code from two versions and the pressure is building to restore the systems. Everyone is panicking and it’s totally legit!

Luckily, there is a Linux utility called diff that has got your back.

What is the diff command in Linux?

Comparing files and finding the differences between them is a widely used operation. This is specially useful when you have to compare complex code or configuration files.

Instead of comparing manually (which has a high chance of human error), Linux gives you a built in and powerful utility called diff . It also saves time.

To compliment diff commands, Linux also provides another command to apply changes from one file to another called patch . In this article, we’ll be looking into these interesting and versatile commands to see how to use them.

diff command syntax

The syntax for diff is shared below:

image-63

In the next example, there are two files that don’t have the same contents. In the output highlighted below, the diff command shows that lines 11 and 14 in showList_v2.js should change to match lines 11 and 13 in showList_v1.js.

image-64

The next way you can use diff is my favorite, as you can see differences side by side.

Just use the -y flag like this:

image-50

The last example I am going to discuss is unified output. This output is often used as input to the patch command. We’ll see how the patch command works as well:

image-67

Below are some other useful flags you can use with diff .

  • -i to ignore case. diff is case sensitive by default.
  • -w to ignore whitespaces in a file. By default whitespaces are considered a difference.
Читайте также:  Listing all directories linux

patch Command Syntax

Changes happen all the time in your code, and it is unrealistic and time-consuming to share edited and fixed files for each change. Usually devs share fixes in the code with the team so they are applied instantly.

And using patches is the safest method to distribute improvements only.

Let’s see how patching works:

image-68

However, there is something wrong in the print function and we need a fixture for that. We send the file print_in_js.js to our colleague who fixes the code and sends it back.

First, our colleague is able to find a type in line #3. They correct the file.

Once file is corrected, and the code is functional, they create a patch.

image-69

Once we have the patch, we apply it as follows:

image-72

And yes – our code is fixed!

Wrapping Up

It is relatively simple and straightforward to create and apply patches using patch and diff .

A similar approach works when you’re using version control systems like Git or SVN. Learning the basics really helps you transition to and understand how version control works, which is an important aspect of software development.

Thanks for reading until the end. I would love to connect with you. You can find me here on twitter. Do share your thoughts.

Источник

Команда diff в Linux: сравниваем два файла

Представьте, что однажды утром вы просыпаетесь и обнаруживаете, чтоб ваши продакшен-системы «лежат» из-за бага, который только предстоит найти. Один из наихудших кошмаров, верно?

Также оказывается, что для восстановления системы вам нужно сравнить код в двух версиях. Давление растет, все вокруг паникуют (и это понятно).

К счастью, в Linux есть утилита под названием diff, которая вам поможет.

Что из себя представляет команда diff в Linux?

Сравнение файлов и поиск различий между ними — широко распространенная операция. Она особенно полезна, когда нужно сравнить сложный код или конфигурационные файлы.

Сравнивать вручную долго и тяжело, к тому же велика вероятность ошибок. Поэтому Linux предоставляет вам мощную встроенную утилиту под названием diff. Ее применение позволяет сэкономить время и силы.

В Linux также есть еще одна команда, которая отлично дополняет diff, — patch. Она позволяет применить изменения из одного файла в другом. В этой статье мы рассмотрим обе команды и их применение на практике.

Синтаксис команды diff

Команда diff имеет следующий синтаксис:

Команда diff сравнивает два файла построчно. При этом первый из файлов она считает нуждающимся в редактировании и приведении к виду второго файла. Второй файл для diff — образец для сравнения.

Поэтому в выводе команды даются указания, что и как нужно изменить, чтобы первый файл стал таким же, как второй.

Читайте также:  Crossover linux установить через терминал

Указания даются при помощи специальных символов:

  • c — CHANGE — изменение, которое нужно внести в указанной строке первого файла
  • d — DELETE — то, что нужно удалить в первом файле
  • a — ADD — то, что нужно добавить в первый файл

Давайте рассмотрим несколько примеров использования команды diff.

Примеры использования команды diff

Чтобы выяснить, являются ли файлы одинаковыми, команда diff дополняется флагом -s . В нашем примере содержимое файлов fileA и sameAsfileA совпадает.

Скриншот консоли: команда diff испольузется с флагом -s

А в следующем примере файлы имеют разный контент. Вывод команды diff говорит, что строки 11 и 14 в showList_v2.js нужно изменить, чтобы они совпадали со строками 11 и 13 в showList_v1.js.

Далее мы рассмотрим мой любимый способ использования команды diff — параллельный просмотр изменений. Для этого нужно применить флаг -y:

Параллельный просмотр различий в двух файлах, когда команда diff применяется с флагом -y

И последний пример — с объединенным выводом. Такой output часто используется как input для команды patch (ее мы тоже рассмотрим):

Вот еще несколько полезных флагов, которые можно применять с командой diff:

  • -i — для игнорирования регистра. По умолчанию команда diff учитывает регистр.
  • -w — для игнорирования пробелов в файле. По умолчанию пробелы тоже учитываются и могут считаться различием.

Синтаксис команды patch

Изменения в коде происходят постоянно. Расшаривать отредактированные файлы после внесения каждого изменения нереально. Обычно разработчики расшаривают сами изменения в коде.

Использование патчей («заплаток») — самый безопасный способ делиться только лишь изменениями.

Давайте посмотрим, как работают патчи:

Примеры использования команды patch

Предположим, у нас есть простой JavaScript-код в файле print_in_js.js, который выводит строку.

Но в функции вывода что-то сломалось, и нам нужно внести исправления. Мы отсылаем файл print_in_js.js коллеге, который может исправить код.

Наш коллега находит опечатку в строке № 3 и исправляет файл.

Когда файл исправлен и код работает корректно, наш коллега создает патч:

diff -u print_in_js.js print_in_js_Fixed.js > patched_print_js.diff

Давайте посмотрим содержимое патча:

Получив патч, мы применяем его:

И — вуаля! — наш код исправлен!

Итоги

Создавать и применять патчи при помощи команд patch и diff довольно просто.

Похожий подход применяется, когда вы пользуетесь системами контроля версий вроде Git или SVN. Знание основ (т. е. работы соответствующих команд Linux) поможет вам лучше понять работу систем контроля версий, а это важно для разработчиков.

Источник

How to Run “patch” Command in Linux?

The “patch” is a command for adding patch files to source code or text files. It takes input as a patch file and applies differences to original files. We use the “diff” tool to get the difference.

The “diff” is abbreviated as “differences” and is used to compare the content of two files and list the changes in standard output.

Читайте также:  Mint linux official site

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 [ options ] [ originalfile [ 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:

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.

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.

About the author

Aqsa Maqbool

As a Software engineer, I am passionate to write about various IT related
articles but have deep interest in Linux. I spend most of my time reading Linux related blogs and IT related books. I want to serve the world with my writing skills.

Источник

Оцените статью
Adblock
detector