Which of the following shell redirections will write standard output and standard error output to a file named filename?

A.

2>&1 >filename

B.

>filename 2>&1

C.

1>&2>filename

D.

>>filename

E.

1&2>filename

题解

选项 A,乍看之下很像是将错误输出串流导向到标准输出串流,再把标准输出串流导向到文件串流,所以错误输出串流会流向到文件串流。其实并不是这样。指令的串流导向有点像是指派操作符「=」(assign),如这个选项是将原先接到错误输出串流的接口 2 改至接口 1 接到的标准输出串流,再把原先接到标准输出串流的接口 1 改至文件串流。

写成程序就像是:

port1 = stdout;
port2 = stderr;

port2 = port1; // port2 = stdout
port1 = file; // port1 = file

选项 B,将接口 1 改至文件串流,再将接口 2 改至接口 1 接到的文件串流,所以接口 2 也是接到文件串流。

写成程序就像是:

port1 = stdout;
port2 = stderr;

port1 = file; // port1 = file
port2 = port1; // port2 = file

选项 C,将接口 1 改至接口 2 接到的错误输出串流,再将接口 1 改至文件串流。

写成程序就像是:

port1 = stdout;
port2 = stderr;

port1 = port2; // port1 = stderr
port1 = file; // port1 = file, port2 = stderr

选项 D,将输出串流导向并添加到文件。

选项 E,错误的用法。