Linux Administration
medium
Pregunta de Linux Administration #019e3987
Enunciado de la Pregunta
Linux Administration
#shell-redirection
#stdout
#stderr
#file-descriptor
#2>&1
Medio
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
Correcto
C
1>&2>filename
D
filename
E
1&2>filename
Explicación Oficial / Explicaciones de la Comunidad
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
>filenameredirects file descriptor 1 (stdout) to the filefilename.2>&1redirects 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>&1correctly 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 >filenameredirects 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>filenameis syntactically invalid. The correct syntax for duplicating a file descriptor isn>&m, notn>&m>filename. This would be interpreted as redirecting stdout to stderr, then attempting to redirect something to a file, but the syntax is incorrect.>>filenameappends stdout to the file but does not redirect stderr at all; stderr remains on the terminal.1&2>filenameis 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 named2>filename? Actually,1&2>filenameis ambiguous and not valid shell syntax.