nerdexam
CompTIA

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.

GNU and Unix Commands

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)
  • B
    93% (28)
  • C
    3% (1)
  • D
    3% (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.

A2>&1 >filename

'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.

B>filename 2>&1Correct

'>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.

C1>&2>filename

'1>&2>filename' is not valid shell syntax and does not correctly redirect both streams to a single file.

D>>filename

'>>filename' only appends stdout to 'filename' in append mode and does not redirect stderr at all.

E1&2>filename

'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

#shell redirection#stdout#stderr#file descriptor

Community Discussion

No community discussion yet for this question.

Full LX0-103 Practice