Question

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.

Était-ce utile?

La solution

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

python3 program.py | diff - compare_file.txt

Autres conseils

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.

Try this one:

python3 program.py > redirect_file.txt && diff redirect_file.txt compare_file.txt
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top