Command output redirect to file and terminal
LinuxBashRedirectLinux 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