Skip to content

Spot the difference: diff

IntermediateLesson 23 of 666 min

Compare two versions of a file with diff, read its < and > lines, switch to the unified -u format git uses, and undo one change. Practise in your browser.

Something stopped working after a change, and you want to know exactly what changed. diff compares two files line by line and prints only the lines that differ.

diff settings.conf.orig settings.conf

Put the old file first and the new one second. Then:

  • < lines come from the first (old) file, > lines from the second (new) one;
  • a header such as 2,3c2,3 says which lines: here lines 2 to 3 changed; a means added and d deleted.

No output means the files are the same.

The unified format

diff -u prints the format that git, code reviews and patches use: - for a removed line, + for an added one, and a few unchanged lines around each change so you can see where you are.

diff -u settings.conf.orig settings.conf

diff -q only says whether two files differ, and -i and -w ignore differences in case and in spaces.

Tip:diff ends with status 1 when the files differ and 0 when they're the same, so scripts can use it to ask "did anything change?".

Your turn

Someone changed settings.conf overnight. Compare it with yesterday’s copy, settings.conf.orig, first in diff’s normal format and then with -u. Then put the port back to 8080 in settings.conf, keeping the other changes.

Next