Comparing Directories

Thu, May 29

The typical use of diff from within a terminal (using the default Bash shell) is to compare files. However, with a little slight of hand, known a process substitution, we can use diff to compare the contents of two directories.

The syntax looks as follows:



Commands represents a single command (such as find) or a piped list of commands. The end result of using process substitution is that the commands act as a file. In the first example, the process substitution results in what looks like a file that can be fed into another command. The second example is the opposite, the process substitution enables one or more commands to act as a file for input. Let’s look at how we can use process substitution for comparing directories.

Let’s say we want to compare the contents of the two directories above. The screenshot was captured from Finder, and in this case, provides a concise view of each directory. However, if the directories are not as conveniently located (in the same sub-directory) or have many more files, or if you need to compare directories from within a terminal, then you could run the following from a terminal:

$ diff <(find tmp1) <(find tmp2)

Here we use the find command to walk through the directories. Using the process substitution, the results of the find command look as though they are files, which enables us to feed both into diff.

You can learn more about process substitution on the Bash man page at the Apple Developer Connection.

One comment

Thank you for a great article on process substitution. I have to point out that diff itself is flexible enough to allow you to use it to compare directories (and recursively compare subdirectories) without process substitution. I’m not an expert on the history of diff, so I can only tell you that this works on Leopard’s diff (10.5.3), and on the version of linux that was installed in the lab when I was a TA.

by Adam Faeth on Jun 9, 2008. #