Command output redirect to file and terminal

LinuxBashRedirect

Linux Problem Overview


I am trying to throw command output to file plus console also. This is because i want to keep record of output in file. I am doing following and it appending to file but not printing ls output on terminal.

$ls 2>&1 > /tmp/ls.txt

Linux Solutions


Solution 1 - Linux

Yes, if you redirect the output, it won't appear on the console. Use tee.

ls 2>&1 | tee /tmp/ls.txt

Solution 2 - Linux

It is worth mentioning that 2>&1 means that standard error will be redirected too, together with standard output. So

someCommand | tee someFile

gives you just the standard output in the file, but not the standard error: standard error will appear in console only. To get standard error in the file too, you can use

someCommand 2>&1 | tee someFile

(source: https://stackoverflow.com/questions/818255/in-the-shell-what-is-21 ). Finally, both the above commands will truncate the file and start clear. If you use a sequence of commands, you may want to get output&error of all of them, one after another. In this case you can use -a flag to "tee" command:

someCommand 2>&1 | tee -a someFile

Solution 3 - Linux

In case somebody needs to append the output and not overriding, it is possible to use "-a" or "--append" option of "tee" command :

ls 2>&1 | tee -a /tmp/ls.txt
ls 2>&1 | tee --append /tmp/ls.txt

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSatishView Question on Stackoverflow
Solution 1 - LinuxKaroly HorvathView Answer on Stackoverflow
Solution 2 - LinuxSerge RogatchView Answer on Stackoverflow
Solution 3 - LinuxFarahView Answer on Stackoverflow