Search code examples
bashshellpipelineio-redirection

How do I print STDERR from a subshell?


Using the answer found in How can you diff two pipelines in Bash? I have written some shell scripts that I want to compare the output of:

diff <(script1 | script2) <(script3 | script4)

However, any errors printed to STDERR in any of the scripts in the subshell pipelines disappear. How can I get them to print in my outer level script (that contains the diff)?


Solution

  • The error messages from scripts 1..4 shouldn't vanish down a black hole; you only redirected their standard output as the files given to diff.

    For example, given these files:

    $ cat script1
    #!/bin/bash
    echo $0 stdout
    echo $0 stderr >&2
    $ cat script2
    #!/bin/bash
    echo $0 stdout
    cat -
    echo $0 stderr >&2
    $ cat script3
    #!/bin/bash
    echo $0 stdout
    echo $0 stderr >&2
    $ cat script4
    #!/bin/bash
    echo $0 stdout
    cat -
    echo $0 stderr >&2
    $
    

    The output from your command line is:

    $ diff <(script1 | script2) <(script3 | script4)
    ./script1 stderr
    ./script3 stderr
    ./script2 stderr
    ./script4 stderr
    1,2c1,2
    < ./script2 stdout
    < ./script1 stdout
    ---
    > ./script4 stdout
    > ./script3 stdout
    $