Shell – How to Diff a File and Output from the Command

io-redirectionshell

Normally you would write:

diff file1 file2

But I would like to diff a file and output from the command (here I make command a trivial one):

diff file1 <(cat file2 | sort)

Ok, this work when I enter this manually at shell prompt, but when I put exactly the same line in shell script, and then run the script, I get error.

So, the question is — how to do this correctly?

Of course I would like avoid writing the output to a temporary file.

Best Answer

I suspect your script and your shell are different. Perhaps you have #!/bin/sh at the top of your script as the interpreter but you are using bash as your personal shell. You can find out what shell you run in a terminal by running echo $SHELL.

An easier way to do this which should work across most shells would be to use a pipe redirect instead of the file read operator you give. The symbol '-' is a standard nomenclature for reading STDIN and can frequently be used as a replacement for a file name in an argument list:

cat file2 | sort | diff file1 -

Or to avoid a useless use of cat:

sort < file2 | diff file1 -