111

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

160

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

ls 2>&1 | tee /tmp/ls.txt
Sign up to request clarification or add additional context in comments.

11 Comments

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).
How do i append logs using tee?
nevermind i found it --append, -a
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...)
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.
|
61

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

Comments

24

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.