Linux Administration
medium

Questão de Linux Administration #019e3987

Enunciado da Questão
Linux Administration
#shell-redirection
#stdout
#stderr
#file-descriptor
#2>&1
Médio

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

Correta
C

1>&2>filename

D

filename

E

1&2>filename

Explicação Oficial / Explicações da Comunidade

The correct shell redirection to write both standard output (stdout) and standard error (stderr) to a file named filename is >filename 2>&1. This works by first redirecting stdout to the file, then redirecting stderr (file descriptor 2) to wherever stdout (file descriptor 1) is currently pointing, which is the file.

How it Works

  • >filename redirects file descriptor 1 (stdout) to the file filename.
  • 2>&1 redirects file descriptor 2 (stderr) to the current target of file descriptor 1, which is now the file.
  • The order is critical: stdout must be redirected to the file before stderr is redirected to stdout.

Why the Correct Value is Right

  • >filename 2>&1 correctly combines both streams into the file because the redirections are evaluated left-to-right. First, stdout is sent to the file; then, stderr is sent to the same place as stdout (the file).

Why the Incorrect Values are Wrong

  • 2>&1 >filename redirects stderr to the current stdout (which is the terminal by default), then redirects stdout to the file. As a result, only stdout goes to the file; stderr still goes to the terminal.
  • 1>&2>filename is syntactically invalid. The correct syntax for duplicating a file descriptor is n>&m, not n>&m>filename. This would be interpreted as redirecting stdout to stderr, then attempting to redirect something to a file, but the syntax is incorrect.
  • >>filename appends stdout to the file but does not redirect stderr at all; stderr remains on the terminal.
  • 1&2>filename is syntactically invalid. The ampersand must be placed before the file descriptor number in a duplicate redirection (e.g., 2>&1), not after. This would be interpreted as redirecting file descriptor 1 to a file named 2>filename? Actually, 1&2>filename is ambiguous and not valid shell syntax.