Linux commands
Browse topics

Comparing files and applying changes with diff and patch

Version
unversioned
Review
Draft

Summary#

diff shows how two files differ. A unified diff can be saved and applied to another copy with patch.

Syntax#

sh
diff -u old.conf new.conf
diff -ru old-dir new-dir
cmp -s a.bin b.bin
patch --dry-run old.conf < change.patch
patch old.conf < change.patch
patch -p1 < project.patch

-u prints context in unified format and -r compares directories. cmp compares bytes. --dry-run reports what patch would do, and -p1 removes the first directory from the file names in the patch.

Example#

sh
(
  set -eu
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT
  cd "$dir"
  printf '%s\n' 'port=80' 'debug=on' > app.conf
  printf '%s\n' 'port=80' 'debug=off' > new.conf

  status=0
  diff -u app.conf new.conf > change.patch || status=$?
  echo "diff status: $status"
  grep '^[-+]debug' change.patch

  patch --quiet app.conf < change.patch
  cmp -s app.conf new.conf && echo 'files are identical'
)

Expected output#

Text
diff status: 1
-debug=on
+debug=off
files are identical

Common mistakes#

diff and cmp exit with 0 for equal files, 1 for differences and 2 for trouble, so handle status 1 under set -e. Applying a patch twice makes patch ask about a Reversed (or previously applied) patch detected; do not accept reversal without checking what you want. Hunk #1 FAILED means the target no longer matches the patch context; patch saves rejected hunks in a .rej file. Run --dry-run first, and use git apply for patches that carry Git-specific changes.

Version applicability#

This entry describes GNU diffutils 3.12 and GNU patch. BSD and macOS tools support fewer options.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0