bashcommand-substitution

How does piping input work when only a subshell, not the command directly on the right-hand side, reads it?


Could someone tell me why this command

echo "1 2 3" | echo "$[$(tr ' ' '+')]"

can print '6' after being executed. Actually, output from echo "1 2 3" can't be passed to tr by pipe, so where is the source of reading to tr.

I want know the details of executing of the command above.


Solution

  • Let's consider echo "$[$(tr ' ' '+')]" on its own - the "inner" most tr is executed firt, and waits for stdin input. If you run it on its own, you'll see it block and waits for stdin, which you can provide manually (followed by a CTRL+D).

    Comments added for annotation - don't type them in verbatim, it won't work:

    user@machine$ echo "$[$(tr ' ' '+')]"
    # Command blocks for stdin
    # We enter some input:
    1+2+3
    # Now we press CTRL+D
    # and get this output:
    6
    

    The echo replaces the manual input to stdin.