0

I was finding a way to save all output to a file and print it.

And the command like the following does work perfectly!

ls "*" 2>&1 | tee ls.txt

But I think I don't understand it well.

And I tried ls "*" | tee ls.txt. It doesn't work. The error message was not saved into ls.txt.

Also I tried ls "*" 1>&2 | tee ls.txt. It behaved some strange. What happened?

pktangyue
  • 8,326
  • 9
  • 48
  • 71

3 Answers3

2

2>&1 says "redirect stderr (2) to wherever stdout (1) goes". 1 and 2 are the file descriptors of stdout and stderr respectively.

When you pipe ls output to tee, only stdout goes to tee (without 2>&1). Hence, the error messages are not saved into ls.txt.

P.P
  • 117,907
  • 20
  • 175
  • 238
0

You can actually use:

ls "*" |& tee ls.txt

to pipe both stdout and stderr to tee command.

ls '*' is actually trying to list a file with the name as * since '*' is inside the quotes.

Your command:

ls '*' 2>&1 | tee out

works by by first redirecting stderr(2) to stdout(1) then using the pipe to tee

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

As mentionned by l3x, you are redirecting the "standard error: 2" to "standard output: 1". The solution is to trigger the redirection before the actual error occurs. So instead of using

ls "*" 2>&1 | tee ls.txt

You should use

ls 2>&1 "*" | tee ls.txt

This way the "standard error" will not be empty, and will be redirected to "standard output" and the tee will work because "standard output" will not be empty. I already tested it and it works. I hope that this was helpful

Jody
  • 1
  • 2