Unix Diff

diff is a mightly command line tool found in most of Unix and Unix-like operating systems. diff helps you to find differences between files and directories.

Things You Can Do with Unix Diff

  • Compare files with diff
  • Compare directories with diff
  • Compare binary files with diff
  • Compare backup copies to current files

How To Use Unix Diff

In its simplest form, compares two text files – you provide their names as command line options.

Let’s create two files first:

greys@maverick:~ $ touch try
greys@maverick:~ $ touch try2

Diff won’t show any difference because they’re exactly the same – empty new files:

greys@maverick:~ $ diff try try2

If we change one of the files by adding the hello word to it, see what happens:

greys@maverick:~ $ echo "hello" >> try2
greys@maverick:~ $ diff try try2
0a1
> hello

Diff spotted the difference and indicated, which file has it (> means second file, the file in the right section of the command line).

Now, let’s add something else to the first file to make things a bit more interesting:

greys@maverick:~ $ echo "hi" >> try
greys@maverick:~ $ diff try ttry2
1c1
< hi
---
> hello

See? diff now highlighted that the first file (< pointing to the file in the left part of the command line you specified) also has a line that’s different from second file.

If we now add exactly the same line to both files, diff will ignore it because it only shows what’s different:

greys@maverick:~ $ echo "test" >> try
greys@maverick:~ $ echo "test" >> try2
greys@maverick:~ $ cat try
hi
test
greys@maverick:~ $ cat try2
hello
test
greys@maverick:~ $
greys@maverick:~ $ diff try try2
1c1
< hi
---
> hello

That’s it for today! I’ll show you some advanced usages of the diff command some other time.

See Also

See Also




Keep Learning

Follow me on Facebook, Twitter or Telegram:
Recommended
I learn with Educative: Educative
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!

Recent Tweets