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
jww
  • 97,681
  • 90
  • 411
  • 885
Satish
  • 16,544
  • 29
  • 93
  • 149

3 Answers3

145

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

ls 2>&1 | tee /tmp/ls.txt
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Does it write stderr & stdout both?? – Satish Nov 27 '12 at 19:18
  • 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). – Karoly Horvath Nov 27 '12 at 19:21
  • 1
    How do i append logs using tee? – Satish Nov 27 '12 at 19:59
  • 9
    nevermind i found it --append, -a – Satish Nov 27 '12 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 '14 at 03:59
  • 3
    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`. – Christian Hujer Aug 30 '15 at 16:47
  • Note: in modern versions of bash and zsh, you can use `&>` instead of `2>&1`. https://linux.die.net/man/1/bash – catleeball Jun 12 '20 at 23:12
  • looks like `tee` "eats" colorizing and some formatting (try with `ls`), can we avoid this drawback? May be some option for that? – YakovL Sep 23 '21 at 08:50
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
Serge Rogatch
  • 13,865
  • 7
  • 86
  • 158
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
Farah
  • 2,469
  • 5
  • 31
  • 52