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,錯誤的用法。