19

Let's say I have a script called script, that reads from stdin and spits out some results to the screen.

If I wanted to feed it contents of one file, I would have typed:

$ ./script < file1.txt

But what if I want to feed the contents of the multiple files to the script the same way, is it at all possible? The best I came up with so far was:

cat file1.txt file2.txt > combined.txt && ./script < combined.txt

Which uses two commands and creates a temp file. Is there a way to do the same thing but bypassing creating the combined file?

  • Switch to zsh and you'll be able to run cmd <file1 <file2 ... <fileN ;) – don_crissti Nov 20 '17 at 14:29
19

You can use cat and a pipe:

cat file1 file2 file3 ... fileN | ./script

Your example, using a pipe, and no temp file:

join file1.txt file2.txt | ./script
  • D'oh. It is so simple I am not even sure how I did not realize it myself. Thanks! – 0x4B1D Sep 8 '11 at 1:12
  • 10
    Useful use of cat award! – glenn jackman Sep 8 '11 at 1:58
  • 3
    @Bruce Ediger: I assume you were just pointing out a way to use join without a temp file, but just to make it clear to the reader: cat f1 f2 does not produce the same output as join f1 f2 – Peter.O Sep 8 '11 at 3:04
  • @fred thanks for pointing this out -- I used join in my example because I was playing with it before; in reality, for my example I was using cat. – 0x4B1D Sep 8 '11 at 12:38
9

If you don't want to use a pipe, you can use input redirection with process substitution:

./script <(cat file1 file2)
3

To add on @Jonah Braun's answer, if you ever need to add process output into your script as well, i.e. your file might not be on your disk but accessed via URL using curl or a similar tool.

Something like this could be used to get stdout of multiple processes and use them in a script via stdin

This will be the script to handle input Contents of multi-input.sh:

#!/usr/bin/env bash
while read line; do
    echo $line
done

Now test it:

$ ./multi-input.sh < <(cat <(echo process 1) <(echo process 2) <(echo process 3))

Output:

process 1
process 2
process 3

<() turns process into a virtual file using fd if you will, so < is needed to read it. cat itself doesn't need it because it does what it does, concatenates files, virtual or real.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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