I know how to redirect to a file, and use tee; on a basic level.
So
$ alias outanderr='bash -c "echo stdout >&1; echo stderr >&2"'
# A fake "application" displaying both output and error messages.
$ outanderr 1>file # redirect stdout to a file, display stderr
stderr
$ outanderr 2>file # redirect stderr to a file, display stdout
stdout
$ outanderr 1>file 2>&1 # redirect both to a file, display nothing
$ outanderr | tee file; echo "-- file contents --" && cat file
# redirect stdout to a file, display both (note: order is messed up)
stderr
stdout
-- file contents --
stdout
$ outanderr 2>&1 | tee file; echo "-- file contents --" && cat file
# redirect both to a file, display both
stdout
stderr
-- file contents --
stdout
stderr
The question is: what to write in place of the questionmarks to get the output below:
$ outanderr ???; echo "-- file contents --" && cat file
# redirect both to a file, display stderr
stderr
-- file contents --
stdout
stderr
Constaints:
- Assuming bash.
- The order should be kept in the file.
- stderr contents are displayed in real time line by line, i.e. no buffering.
- Separate script files can be used.
- Magic may be necessary.
Best Answer
For easy testing:
Edit 1:
This works by writing stdout (only) to the file, making sterr stdout so that it goes through the pipe, and having tee write its output to the same file.
Both writes must be done in append mode (
>>
instead of>
) otherwise both would overwrite each others output.As the pipe is a buffer there is no guarantee that the output appears in the file in the right order. This would not even change if an application was connected to both file descriptors (two pipes). For guaranteed order both outputs would have to go through the same channel and be marked respectively. Or you would need some really fancy stuff:
/dev/null
. The outputsĀ of the application would be separated by running it throughstrace -f -s 32000 -e trace=write
. You would have to reverse the escaping in that case. Needless to say that the application does not run faster by being traced.