DEV Community

Cover image for diff and patch explained
Akram Narejo
Akram Narejo

Posted on • Updated on

diff and patch explained

diff and patch are the useful commands which help in updating the file with current changes.

  • diff tells the difference between two files
  • Patch is the difference of two files conceptually but as for command patch updates the file with given changes

Let's create a file demo.py with a command nano demo.py with a print statement inside.

print(hello world)

If we execute demo.py python3 demo.py we will get an error

File "demo.py", line 2
print(hello world)
SyntaxError: invalid syntax

So in this case Let's make an other file demo_fixed.py and correct the error.

print('hello world')

Now if we execute demo_fixed.py file we get the output

hello world

Let's compare the both of files demo.py and demo_fixed.py to see the difference.

diff -u demo.py demo_fixed.py

we get the following changes

--- demo.py 2020-07-30 12:35:50.200813874 +0500
+++ demo_fixed.py 2020-07-30 12:35:35.144740070 +0500
@@ -1,2 +1,2 @@
-print(hello world)
+print('hello world')

- means statement is deleted & + means the statement is added.
Let's write the changes to another file so we can update the changes with original file.

diff -u demo.py dem_fiexed.py > changes.diff

> writes the data & < reads the data

Now let's apply the patch or changes to our actual file

patch demo.py < changes.diff

If we execute the demo.py file now

Python3 demo.py

we get

hello world

Finally we updated our demo.py file with the given patch of changes.

This is my first post so please let me know about the content and if you find it helpful please do appreciate.

Top comments (2)

Collapse
 
jakeerc profile image
Jakeer

Salamalaikum, Jazakallah khair

Helpfull

Collapse
 
akramnarejo profile image
Akram Narejo

wa alaykums-salam brother thanks.