LFCS · Question #808
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. This question assesses the correct syntax for redirecting both standard output (stdout) and standard error (stderr) to the same file in a Bash shell.
Question
Options
- A2>&1 >filename
- B
filename 2>&1
- C1>&2>filename
- D
filename
- E1&2>filename
How the community answered
(30 responses)- B90% (27)
- C7% (2)
- E3% (1)
Why each option
This question assesses the correct syntax for redirecting both standard output (stdout) and standard error (stderr) to the same file in a Bash shell.
`2>&1 >filename` is incorrect because `2>&1` redirects stderr to where stdout currently points (the terminal), and *then* `>filename` redirects only stdout to 'filename', leaving stderr going to the terminal.
The redirection `> filename` first redirects standard output (file descriptor 1) to 'filename'. Then, `2>&1` redirects standard error (file descriptor 2) to the same destination that standard output is currently pointing to, which is now 'filename'. This ensures both streams go to the same file.
`1>&2>filename` is incorrect syntax; `1>&2` would redirect stdout to stderr, and then `>filename` would attempt to redirect stdout (which is now linked to stderr) to the file, but the original stderr would still go to the terminal.
`>>filename` redirects only standard output to 'filename' in append mode, it does not redirect standard error.
`1&2>filename` is incorrect syntax and does not achieve the desired redirection for both streams.
Concept tested: Bash stdout and stderr redirection
Source: https://www.gnu.org/software/bash/manual/bash.html#Redirections
Topics
Community Discussion
No community discussion yet for this question.