Jay Taylor's notes
back to listing indexRedirect stderr and stdout in Bash
[web search]
|
This redirects stderr to the original stdout, not to the file where stdout is going. Put '2>&1' after '>file.log' and it works.
– user25148
Mar 12 '09 at 9:25
|
||||
|
What is the advantage of this approach over some_command &> file.log?
– ubermonkey
May 27 '09 at 14:04
|
||||
|
If you want to append to a file then you must do it this way: echo "foo" 2>&1 1>> bar.txt AFAIK there's no way to append using &>
– SlappyTheFish
Jun 8 '10 at 10:58
|
||||
|
|||||
|
I think the interpretation that 2>&1 redirects stderr to stdout is wrong; I believe it is more accurate to say it sends stderr to the same place that stdout is going at this moment in time. Thus place 2>&1 after the first redirect is essential.
– jdg
Aug 7 '15 at 17:47
|
||||
Now, simple echo will write to $LOG_FILE. Useful for daemonizing. To the author of the original post, It depends what you need to achieve. If you just need to redirect in/out of a command you call from your script, the answers are already given. Mine is about redirecting within current script which affects all commands/built-ins(includes forks) after the mentioned code snippet. Another cool solution is about redirecting to both std-err/out AND to logger or log file at once which involves splitting "a stream" into two. This functionality is provided by 'tee' command which can write/append to several file descriptors(files, sockets, pipes, etc) at once: tee FILE1 FILE2 ... >(cmd1) >(cmd2) ...
So, from the beginning. Let's assume we have terminal connected to /dev/stdout(FD #1) and /dev/stderr(FD #2). In practice, it could be a pipe, socket or whatever.
The result of running a script having the above line and additionally this one:
...is as follows:
If you want to see clearer picture, add these 2 lines to the script:
|