010-100 · Question #34
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. The correct shell redirection syntax to send stdout to a file and silently discard stderr is 'command >file 2>/dev/null'.
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
(71 responses)- A4% (3)
- B1% (1)
- C10% (7)
- D3% (2)
- E82% (58)
Why each option
The correct shell redirection syntax to send stdout to a file and silently discard stderr is 'command >file 2>/dev/null'.
The token '>2>file' is malformed because it does not properly specify file descriptors, and '1&>/dev/null' is not valid syntax for redirecting stdout alone.
The '<' operator redirects stdin, not stdout, so this command reads from a file named 'output' as input and discards stdout to /dev/null, which is the opposite of the intended goal.
Chaining two bare '>' operators as '> discard-error > file' is not valid shell syntax for specifying separate streams; file descriptor numbers must be used explicitly.
This form redirects stdout to /dev/null first (discarding the desired output), uses the malformed token '2&>1' instead of the correct '2>&1', and treats the word 'output' as a command argument rather than a filename.
The token '>file' redirects file descriptor 1 (stdout) to the named file, and '2>/dev/null' explicitly redirects file descriptor 2 (stderr) to /dev/null where it is silently discarded; together these two redirections independently route each output stream to its intended destination without interfering with each other.
Concept tested: Shell I/O redirection of stdout and stderr independently
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.