Using diff and patch

Problem

You can never remember how to use diff to create patches that may later be applied using patch.

Solution

If you are creating a simple patch for a single file, use:

$ diff -u original_file modified_file > your_patch

If you are creating a patch for multiple files in parallel directory structures, use:

$ cp -pR original_dirs/ modified_dirs/

# Make changes here

$ diff -Nru original_dirs/ modified_dirs/ > your_comprehensive_patch

To be especially careful, force diff to treat all files as ASCII using -a, and set your language and timezone to the universal defaults as shown:

$ LC_ALL=C TZ=UTC diff -aNru original_dirs/ modified_dirs/ > your_comprehensive_patch $ LC_ALL=C TZ=UTC diff -aNru original_dirs/ modified_dirs/ diff -aNru original_dirs/changed_file modified_dirs/changed_file --- original_dirs/changed_file 2006-11-23 01:04:07.000000000 +0000 +++ modified_dirs/changed_file 2006-11-23 01:04:35.000000000 +0000 @@ -1,2 +1,2 @@ This file is common to both dirs. -But it changes from one to the other. +But it changes from 1 to the other. diff -aNru original_dirs/only_in_mods modified_dirs/only_in_mods --- original_dirs/only_in_mods 1970-01-01 00:00:00.000000000 +0000 +++ modified_dirs/only_in_mods 2006-11-23 01:05:58.000000000 +0000 @@ -0,0 +1,2 @@ +While this file is only in the modified dirs. +It also has two lines, this is the last. diff -aNru original_dirs/only_in_orig modified_dirs/only_in_orig --- original_dirs/only_in_orig 2006-11-23 01:05:18.000000000 +0000 +++ ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.