Reputation: 108
this fails stderr redirection:
(echo a >/dev/stdout;echo b >/dev/stderr) 2>&1 >test2.log;ls test2.log;cat test2.log
so, the above will output: "b" at terminal, and will log "a"
this fails to log stderr too:
(echo a >&1;echo b >&2) 2>&1 >test2.log;ls test2.log;cat test2.log
this vanishes with stdout and logs stderr:
(echo a >/dev/stdout;echo b >/dev/stderr) &>test2.log;ls test2.log;cat test2.log
this fully works:
(echo a >&1;echo b >&2) &>test2.log;ls test2.log;cat test2.log
is this some bug related to the way things should be outputted or I am missing some knowledge?
Obs.: I found this problem because I wasnt being able to log strace dosbox
, this is NOT a dosbox question, this is just a comment to say that the origin of the problem was found on a non script application (could be any other application...), and I was able to replicate the problem on a command line terminal in a script way.
PS.: ubuntu 16.04.1 , bash 4.3.48(1)
Upvotes: 2
Views: 1789
Reputation: 531035
The key is to recognize that the shell first processes the redirections outside the subshell from left to write; the resulting file descriptors are then inherited by the subshell.
With this
(echo a >/dev/stdout;echo b >/dev/stderr) 2>&1 >test2.log
ls test2.log
cat test2.log
The shell starts by processing 2>&1
, which sends standard error to the same place as standard output (here, the terminal). The next redirection makes test2.log
the standard output, without affecting standard error.
Now, the subshell inherits those file descriptors, so a
is written to the inherited standard output (i.e., test2.log
) and b
is written to the inherited standard error (i.e., the terminal).
Upvotes: 2
Reputation: 361585
# Wrong
(echo a >/dev/stdout;echo b >/dev/stderr) 2>&1 >test2.log
This first redirects stderr to where stdout is pointing: the console. Then it redirects stdout to test2.log
. The second redirection doesn't affect the first. The end result is that stderr is still visible, it isn't logged.
# Right
(echo a >/dev/stdout;echo b >/dev/stderr) >test2.log 2>&1
Solution: swap the order of the redirections. Reading left to right, you want to redirect stdout to test2.log
, and then redirect stderr to where stdout is pointing: test2.log
.
Upvotes: 3