010-150 · Question #18
How can the normal output of a command be written to a file while discarding the error output?
The correct answer is E. command >file 2>/dev/null. Shell redirection allows stdout and stderr to be sent to separate destinations independently. The correct syntax uses >file for stdout and 2>/dev/null to discard stderr.
Question
How can the normal output of a command be written to a file while discarding the error output?
Options
- Acommand >2>file 1&>/dev/null
- Bcommand < output > /dev/null
- Ccommand > discard-error > file
- Dcommand > /dev/null 2&>1 output
- Ecommand >file 2>/dev/null
How the community answered
(55 responses)- B5% (3)
- C11% (6)
- D2% (1)
- E82% (45)
Why each option
Shell redirection allows stdout and stderr to be sent to separate destinations independently. The correct syntax uses `>file` for stdout and `2>/dev/null` to discard stderr.
The token `>2>file` is not valid redirection syntax, and `1&>/dev/null` would send stdout to null rather than to a file.
The `<` operator performs input redirection, not output redirection, and this syntax does not write command output to any file.
`> discard-error > file` is not valid shell syntax; you cannot chain two `>` redirects this way to control stdout and stderr separately.
`2&>1` is not valid syntax (the correct form is `2>&1`), the word `output` is treated as a filename argument rather than a redirect target, and the logic is inverted from the requirement.
The syntax `command >file 2>/dev/null` correctly redirects file descriptor 1 (stdout) to the named file using `>file`, and separately redirects file descriptor 2 (stderr) to `/dev/null` using `2>/dev/null`, which discards it. These are two independent redirections applied in sequence, achieving exactly the desired behavior.
Concept tested: Linux shell 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.