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

2

6

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:
Resuscitator answered 8/11, 2017 at 14:50 Comment(0)
L
5

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.

Leftward answered 8/11, 2017 at 14:56 Comment(2)
Can stderr be captured from a subshell through command substitution?Resuscitator
Strictly speaking, no. You need to go through some contortions to copy standard out to another file descriptor, copy standard error to standard out, then decide what to do with the original standard out.Leftward
V
1

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

Vitrescent answered 8/11, 2017 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.