Why is stderr from a subshell not being suppressed or redirected?

Viewed 2564

I know that subshells have their stdout suppressed from the caller's output:

a=$(echo 123)
echo a:$a

This outputs, as expected:

a:123

But why isn't stderr suppressed as it's in a subshell?

a=$(>&2 echo 123)

Expected output:

(nothing)

Actual output:

123

Here is a test where stderr should redirect to stdout and be captured to variable a:

a=$(>&2 echo 123 2>&1)
echo a:$a

Expected output:

a:123

Actual output:

123
a:
2 Answers

The output isn't being suppressed; it's being captured. That's the difference between an ordinary subshell (echo foo) and a command substitution a=$(echo foo). Further, a command substitution doesn't capture standard error, only standard output.

Here is a test where stderr should redirect to stdout and be captured to variable a:

a=$(>&2 echo 123 2>&1)

No.

  1. First you redirect fd1 to what fd2 is currently using: >&2 -- now, stdout points to stderr.
  2. Then, you redirect fd2 to what fd1 is currently using: 2>&1 -- now, stderr points to stderr.

If you want stderr to point to stdout, you can't first redirect stdout. Remove the >&2

Related