LX0-103 · Question #208
Which of the following shell redirections will write standard output and standard error output to a file named filename?
The correct answer is B. >filename 2>&1. To redirect both stdout and stderr to the same file, stdout must be redirected to the file first, and then stderr must be redirected to stdout's new destination in that order.
Question
Which of the following shell redirections will write standard output and standard error output to a file named filename?
Options
- A2>&1 >filename
- B
filename 2>&1
- C1>&2>filename
- D
filename
- E1&2>filename
How the community answered
(30 responses)- B93% (28)
- C3% (1)
- D3% (1)
Why each option
To redirect both stdout and stderr to the same file, stdout must be redirected to the file first, and then stderr must be redirected to stdout's new destination in that order.
'2>&1 >filename' redirects stderr to fd 1's current destination (the terminal) before stdout is redirected, so stderr still goes to the terminal while only stdout goes to the file.
'>filename' redirects file descriptor 1 (stdout) to 'filename' first, and then '2>&1' redirects file descriptor 2 (stderr) to wherever fd 1 currently points - which is now 'filename' - so both streams end up written to the same file.
'1>&2>filename' is not valid shell syntax and does not correctly redirect both streams to a single file.
'>>filename' only appends stdout to 'filename' in append mode and does not redirect stderr at all.
'1&2>filename' is not valid shell redirection syntax and is not interpreted as a combined redirect by the shell.
Concept tested: Shell redirection combining stdout and stderr to one file
Source: https://www.gnu.org/software/bash/manual/bash.html#Redirecting-Standard-Output-and-Standard-Error
Topics
Community Discussion
No community discussion yet for this question.