Search code examples
linuxbashoperatorsstdoutstdin

Redirection Operators: two cases


Consider the following command line:

cat <<< "Hello World" > output1.txt > output2.txt ... > outputn.txt

In this case we have <<< here-string operator, which is an input redirection operator. But let's focus on > output redirection operator. It works perfectly, sending channels from cat command output (stdout) to different files output1.txt, output2.txt etc.

Now consider the command line below:

cat < input1.txt < input2.txt ...  < inputn.txt

Similarly to what occurs in the first command line with > output redirection operators, I expected each < input redirection operator sending the files contents to cat command stdin. But instead, cat is catching only the last file content (inputn.txt) ignoring the rest.

Is cat command ignoring < before inputn.txt and reading it as an argument (which is preferred to stdin)? Or inputn.txt was sent to stdin? In this case, why are input1.txt, input2.txt... contents not in stdin stream of cat command?


Solution

  • bash processes redirections left-to-right on the command line before running the process. Each redirection is self-contained and will redirect a file descriptor to/from the file, so if you have multiple redirects that affect the same file descriptor, only the last one will (still) be in effect when the command runs.

    So in your output case

    cat <<< "Hello World" > output1.txt > output2.txt ... > outputn.txt
    

    The output files output1.txt, output2.txt etc will be created but stdout will be left pointing at the last one (outputn.txt) and all the output of cat will go there and the other files will be empty.

    Similarly with the input case

    cat < input1.txt < input2.txt ...  < inputn.txt
    

    each file will be opened, but stdin will be left pointing at the last one, so nothing will be read from the others.