Understanding diff and patch

When working with code, especially with a team, it’s important to handle changes efficiently. Two handy tools for this are diff and patch.

diff

The diff command helps you compare two files line by line and shows you the differences. This makes it easy to see what changes have been made.

Example:

Suppose you have two versions of a Python file, file1.py and file2.py. You want to check what changes were made from file1.py to file2.py.

diff file1.py file2.py

The output might look like this:

3c3
< print("Hello, World!")
---
> print("Hello, Universe!")

This output means that line 3 in file1.py, which prints “Hello, World!”, has been changed to print “Hello, Universe!” in file2.py.

patch

The patch command lets you apply changes to a file based on a diff file. This is useful for sharing updates or fixes without needing to send the entire file.

Example:

You have a diff file, changes.diff, which contains the differences between two versions of a file. You want to apply these changes to file1.py.

patch file1.py < changes.diff

This command updates file1.py with the changes specified in changes.diff.