Redirecting the output of a command to a file and to a terminal

I am also trying to output the output of the command to a file plus the console. This is because I want to save the output record in a file. I do the following and add to the file, but do not print ls output to the terminal.

 $ls 2>&1 > /tmp/ls.txt 
+56
redirect linux bash
Nov 27 '12 at 19:13
source share
3 answers

Yes, if you redirect the output, it will not appear on the console. Use tee .

 ls 2>&1 | tee /tmp/ls.txt 
+90
Nov 27 '12 at 19:16
source share

It should be noted that 2> & 1 means that the standard error will also be redirected along with the standard output. So

 someCommand | tee someFile 

gives you standard output in a file, but not a standard error: a standard error appears only in the console. To get the standard error in the file, you can use

 someCommand 2>&1 | tee someFile 

(source: In the shell, what is "2> & 1", ). Finally, both of the above commands will trim the file and begin cleaning. If you use a sequence of commands, you may want to get the output and the error of all of them one by one. In this case, you can use the -a flag for the "tee" command:

 someCommand 2>&1 | tee -a someFile 
+22
Nov 05 '14 at 12:21
source share

If someone needs to add the output, rather than overriding it, you can use the -e or -append option of the tee command:

 ls 2>&1 | tee -a /tmp/ls.txt ls 2>&1 | tee --append /tmp/ls.txt 
+9
Nov 05 '13 at 11:08
source share



All Articles