97

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
0

3 Answers 3

145

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

ls 2>&1 | tee /tmp/ls.txt
8
  • 3
    In this case error is merged into the output (2>&1), so the next process consuming the pipe will see both of them as regular input (in short: yes). Nov 27, 2012 at 19:21
  • 1
    How do i append logs using tee?
    – Satish
    Nov 27, 2012 at 19:59
  • 9
    nevermind i found it --append, -a
    – Satish
    Nov 27, 2012 at 20:00
  • 2
    How to give the size of ls.txt file in above command so that it does not exceeds that given size. And once it exceeds max size, how to create a new file in that same directory (for eg: ls1.txt,ls2.txt...)
    – Binay
    Jan 21, 2014 at 3:59
  • 4
    Be aware that you will loose the exit status of ls. If you want to retain the exit status of ls, or more precisely want to figure out if something in your pipe failed despite tee being the last (and very likely successful) command in your pipe, you need to use set -o pipefail. Aug 30, 2015 at 16:47
54

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: In the shell, what is " 2>&1 "? ). 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
22

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
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.