How can I redirect and append both stdout and stderr to a file with Bash?
To redirect stdout to a truncated file in Bash, I know to use:
cmd > file.txt
To redirect stdout in Bash, appending to a file, I know to use:
cmd >> file.txt
To redirect both stdout and stderr to a truncated file, I know to use:
cmd &> file.txt
How do I redirect both stdout and stderr appending to a file? cmd &>> file.txt
did not work for me.
cmd >>file.txt 2>&1
Bash executes the redirects from left to right as follows:
>>file.txt
: Open file.txt
in append mode and redirect stdout
there. 2>&1
: Redirect stderr
to "where stdout
is currently going". In this case, that is a file opened in append mode. In other words, the &1
reuses the file descriptor which stdout
currently uses. There are two ways to do this, depending on your Bash version.
The classic and portable ( Bash pre-4 ) way is:
cmd >> outfile 2>&1
A nonportable way, starting with Bash 4 is
cmd &>> outfile
(analog to &> outfile
)
For good coding style, you should
If your script already starts with #!/bin/sh
(no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.
Also remember that Bash 4 &>>
is just shorter syntax — it does not introduce any new functionality or anything like that.
The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output
In Bash you can also explicitly specify your redirects to different files:
cmd >log.out 2>log_error.out
Appending would be:
cmd >>log.out 2>>log_error.out
链接地址: http://www.djcxy.com/p/5922.html
上一篇: 自定义NSURLProtocol的类型?