回显到 stderr 并将 stderr 输出到文件
Echo to stderr and output stderr to a file
我试图将输出回显到 stderr,同时将 stderr 重定向到一个文件,我注意到重定向的顺序很重要,但我不明白为什么必须这样。
文件 asap
为空,使用以下任一命令:
echo "Fatal error." >&2 2>asap
echo >&2 "Fatal error." 2>asap
但这行得通,将 "Fatal error" 记录到文件 asap
。
echo "Fatal error." 2>asap >&2
为什么?
有关详细信息,请参阅 How to pipe stderr and not stdout for most of the required information. Note the 'au contraire' comment, in particular. Remember that all redirections are completed before the command is executed, and that the redirections are processed from left to right. (Pipelines marginally complicate the story. Most of the time, the pipe redirection of standard output is done before any other redirection. The exception is a Bash-specific syntax, |&
. Go read the Bash manual — 然后不要使用 |&
。)
请注意,重定向可以位于命令行中相对于命令名称和参数的任何位置。即:
<html> xml some -command
与
相同
some -command <html >xml
等等。因此,问题中的前两个命令之间没有区别。 (我想你自己发现了。)
问题中的第一个命令:
echo "Fatal error." >&2 2>asap
先将标准输出重定向到当前标准错误,再将标准错误重定向到文件(让标准输出指向原来的标准错误),然后执行echo
命令。该消息转到原始标准错误(您的终端),而不是文件,因为 echo
不写入标准错误。
最后一条命令:
echo "Fatal error." 2>asap >&2
首先将标准错误发送到文件,然后将标准输出发送到标准错误要去的地方(文件),然后执行echo
命令。由于标准输出将转到文件,因此终端上看不到任何内容。
重定向从左到右发生,因此它们可以根据位置采取不同的行为。
例如两条命令:
runme >somefile 2>&1
runme 2>&1 >somefile
因顺序不同有不同效果。
首先将标准输出指向文件somefile
,然后将标准错误指向新的标准输出(文件)。
第二个将标准错误指向当前标准输出(终端,最有可能)然后将标准输出指向文件。
我试图将输出回显到 stderr,同时将 stderr 重定向到一个文件,我注意到重定向的顺序很重要,但我不明白为什么必须这样。
文件 asap
为空,使用以下任一命令:
echo "Fatal error." >&2 2>asap
echo >&2 "Fatal error." 2>asap
但这行得通,将 "Fatal error" 记录到文件 asap
。
echo "Fatal error." 2>asap >&2
为什么?
有关详细信息,请参阅 How to pipe stderr and not stdout for most of the required information. Note the 'au contraire' comment, in particular. Remember that all redirections are completed before the command is executed, and that the redirections are processed from left to right. (Pipelines marginally complicate the story. Most of the time, the pipe redirection of standard output is done before any other redirection. The exception is a Bash-specific syntax, |&
. Go read the Bash manual — 然后不要使用 |&
。)
请注意,重定向可以位于命令行中相对于命令名称和参数的任何位置。即:
<html> xml some -command
与
相同some -command <html >xml
等等。因此,问题中的前两个命令之间没有区别。 (我想你自己发现了。)
问题中的第一个命令:
echo "Fatal error." >&2 2>asap
先将标准输出重定向到当前标准错误,再将标准错误重定向到文件(让标准输出指向原来的标准错误),然后执行echo
命令。该消息转到原始标准错误(您的终端),而不是文件,因为 echo
不写入标准错误。
最后一条命令:
echo "Fatal error." 2>asap >&2
首先将标准错误发送到文件,然后将标准输出发送到标准错误要去的地方(文件),然后执行echo
命令。由于标准输出将转到文件,因此终端上看不到任何内容。
重定向从左到右发生,因此它们可以根据位置采取不同的行为。
例如两条命令:
runme >somefile 2>&1
runme 2>&1 >somefile
因顺序不同有不同效果。
首先将标准输出指向文件somefile
,然后将标准错误指向新的标准输出(文件)。
第二个将标准错误指向当前标准输出(终端,最有可能)然后将标准输出指向文件。