1

I'm trying to execute a Python program, redirect its output to a file, and compare the contents of that file to an existing one, all in a single shell command. This is what I have, but of course it's not working:

diff `python3 program.py > redirect_file.txt` compare_file.txt

I'm a Linux noob, so any help in pointing me in the right direction would be great.

1
  • You need to redirect the output of the script to a file, or you just want to compare it to another file? Jan 19, 2014 at 20:41

3 Answers 3

9

The diff command allows you to use a - on the command line to use stdin, so try:

python3 program.py | diff - compare_file.txt
1
  • +1 absolutely the best way to do this. Now that we're talking Unix, you should add a shebang line so that you don't need to explicitly specify the interpreter.
    – Cu3PO42
    Jan 19, 2014 at 21:03
5

Your command

diff `python3 program.py > redirect_file.txt` compare_file.txt

does not work because of incorrect use of backticks. Backticks differ from double quotes just in that their contents is evaluated by shell and replaced by its standard output. Because you redirected the command’s standard output to a file, backticks now evaluate to empty string. Thus your command is equivalent to:

python3 program.py > redirect_file.txt
diff "" compare_file.txt

But you want:

python3 program.py > redirect_file.txt
diff redirect_file.txt compare_file.txt

If the redirect_file.txt is used just for the diff, you can avoid creating it and speed up the process:

python3 program.py | diff - compare_file.txt

This uses pipe (|), which basically connects standard output of the command on the left to standard input of the command on the right. Diff reads standard input when - is given instead of actual file name, which is a pretty common convention among shell utilities.

You could also use Bash-specific syntax

diff <(python3 program.py) compare_file.txt

but this is not as portable and creates a named pipe, which is unnecessary and potential source of trouble.

1
  • +1 for an answer that's actually better and more exhaustive than mine, and deserves more upvotes. Jan 19, 2014 at 22:22
4

Try this one:

python3 program.py > redirect_file.txt && diff redirect_file.txt compare_file.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.