Viewing and processing text

Command diff

Compare files line by line

Linux · Bash examples · commands run on the selected server

When to use diff

Use diff to compare text or directory contents before replacing configuration files. A reported difference is a normal result, not necessarily a command failure, and scripts must distinguish its exit statuses.

Syntax

diff [OPTIONS] FILE1 FILE2

Square brackets mark optional arguments; an ellipsis means repetition. Replace example file names, user names and server addresses with your own values.

Common options and arguments

-u
Unified difference format with context.
-r
Recursively compare directories.
-q
Report only if there are differences.

Usage examples

Compare configurations

diff -u ./app.conf ./app.conf.bak

Unified output shows changed lines with surrounding context; the source files are not modified.

Compare directories

diff -qr ./release-old ./release-new

Directory trees are compared recursively and differing paths are summarized.

Save patch

diff -u ./old.txt ./new.txt > ./changes.patch

A patch is written to a separate file, replacing an existing patch at that path.

Notes and limitations

  • An exit code of 0 means a match, 1 means a difference, and greater than 1 means an error.
  • The order of the arguments determines the direction of changes in the patch.

Common questions and troubleshooting

Why does a successful comparison return status 1?

For diff, status 1 means differences were found, while 0 means no differences. A higher status signals a problem with the comparison.

Does diff update the old file?

No. It reports differences. Applying a patch is a separate action that should be reviewed and tested on the intended version.

Further help

Options vary by version and distribution. Check the installed documentation with this command: man diff.