2

Given a pipe of the form C1 | C2, if C2 takes more than one positional argument, is it possible to choose where the output of C1 is going?

Consider the following example.

$ cat myscript 
#!/bin/bash
cat $1
cat $2
$ cat world.txt
World
$ echo "Hello" | ./myscript world.txt
World
Hello

I want the final output to be in correct order (Hello World) by altering only the right side of the pipeline.

3
  • 4
    C1 output is not going into $2. Add echo <$2> to the script and you will see that. So the whole premise of your question is not correct.
    – kaylum
    Jan 11, 2020 at 8:51
  • 1
    The pipe connects the stdout of one program to the stdin of the other. It has nothing to do with the script arguments. What you see happening is that $2 is actually empty in your example so the last cat reads from stdin which then comes from the pipe.
    – kaylum
    Jan 11, 2020 at 8:54
  • Also your script is just re-implementing cat. cat (concatenate) will read all files mentioned in its argument lists and output them one after another. Same as what your script is trying to do, but for more and less than 2. Jan 11, 2020 at 10:15

1 Answer 1

5

You might want to try this:

echo "Hello" | ./myscript /dev/stdin world.txt

So that standard input of ./myscript feeds into the first "cat"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .