Linux and Command-Line Basics

$ ls
a.txt
$ ls a.txt nofile 2>&1 > out.txt

As shown above, in a directory where a.txt exists and nofile does not, the last command is run. Which of the following is the result?

  1. AOnly the error line is written to out.txt, and the a.txt line is shown on the screen
  2. BBoth the error line and the a.txt line are written to out.txt, and nothing is shown on the screen
  3. COnly the a.txt line is written to out.txt, and the error line is shown on the screen
Show answer and explanation

Answer: C. Only the a.txt line is written to out.txt, and the error line is shown on the screen

Redirections are processed from left to right. "2>&1" means "send standard error (2) to where standard output (1) goes at that moment", and at that point standard output is still the screen, so errors appear on the screen. The following "> out.txt" changes only standard output to out.txt, so the file receives only the a.txt line, which is the normal output of ls. To write both to the file, change standard output first and then write 2>&1, as in "ls a.txt nofile > out.txt 2>&1".

  • A. 2>&1 points standard error to where standard output goes "at that moment", that is, the screen. The error does not go into out.txt.
  • B. This is the result when written in the order "> out.txt 2>&1". Swapping the order changes the result.
  • C. Correct. At the time of 2>&1 standard output is the screen, so the error appears on the screen.
Practice this topic Back to topic

Books on Linux and Command-Line Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Linux and Command-Line Basics questions

  1. In the session above, which of the following is the value printed by the last command?
  2. In the session above, which of the following are the lines printed by the last grep?
  3. The choices omit the leading spaces of the line. In the session above, which of the following is the line printed by the last pipeline?
  4. You want to keep showing lines on the screen as they are appended later to the server log file /var/log/app.log. Which of the following commands is appropriate?
  5. Which of the following is the output of the command above, which extracts columns from a comma-separated line?