Linux and Command-Line Basics
$ ls
a.txt
$ ls a.txt nofile 2>&1 > out.txtAs 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?
- AOnly the error line is written to out.txt, and the a.txt line is shown on the screen
- BBoth the error line and the a.txt line are written to out.txt, and nothing is shown on the screen
- 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.