Search code examples
bashpipetemporary-files

Redirecting the input of two commands via pipe operator in Bash


I have not learned Bash in a formal way so please do give me suggestions for a more descriptive question title.

Instead of creating a temporary file whose lifespan is limited to that of the command it is used by (in this case, command), as in:

zcat input.txt.gz > input.txt
command input.txt
rm input.txt

we can avoid it as follows:

zcat input.txt.gz | command -

Now my question is whether this is possible with two inputs. I wish to avoid creating two temporary files, as in:

zcat input1.txt.gz > input1.txt
zcat input2.txt.gz > input2.txt
command input1.txt input2.txt
rm input1.txt input2.txt 

I am guessing that the following solution can remove the need to create one of the two temporary files, as:

zcat input1.txt.gz > input1.txt
zcat input2.txt.gz | command input1.txt -
rm input1.txt

but I wonder if there is a way to completely avoid creating the temporary file.

I hope my question was clear enough. Though I used zcat as an example, the solution I am looking for should be more general. Thanks in advance.


Solution

  • If you're trying to combine the output of multiple commands into a single pipe, use a subshell:

    (cat file1.txt; cat file2.txt) | nl
    

    If you want to use the output of a command as a filename for a command, use process substitution:

    diff <(zcat file1.gz) <(zcat file2.gz)