Today's article was hard to title...

KGIII

Super Moderator
Staff member
Gold Supporter
Joined
Jul 23, 2020
Messages
12,659
Reaction score
11,613
Credits
104,317
Have you ever tried to have your terminal's output show both in the terminal and be saved to a file?

Have you ever tried to condense that into a headline that search engines like? I suspect not.


Well, you can and a little bit of tee can help you.
 


Nice one David.

Your call on whether a codicil needs to be added that this applies under a Bash shell.

If The Viewers are using a C Shell

2>&1

is replaced by

Code:
>&

I am not sure if other shells vary.

Cheers

Wiz
 
The tee command sends standard input to standard output by default to the tee file, so in the example in the linux-tips article, using the output of the uptime command, the redirection of standard error to standard output makes no difference, i.e. the addition of the redirection 2>&1 shows no effect because there is no error in the output of the uptime command. Hence the content of the output file is the same whether the redirection is used or not, shown here:
Code:
[tom@min ~]$ uptime | tee uptime.txt
 17:38:23 up 12:13,  2 users,  load average: 0.04, 0.03, 0.04

[tom@min ~]$ cat uptime.txt
 17:38:23 up 12:13,  2 users,  load average: 0.04, 0.03, 0.04

[tom@min ~]$ uptime 2>&1 | tee uptime2.txt
 17:38:59 up 12:14,  2 users,  load average: 0.02, 0.02, 0.04

[tom@min ~]$ cat uptime2.txt
 17:38:59 up 12:14,  2 users,  load average: 0.02, 0.02, 0.04

However, when there is an actual error, it does make a difference, because tee doesn't send standard error to the tee file by default. Below is an example of an error which is not sent to the tee file without the redirection of standard error, but the inclusion of 2>&1 catches the error, shown here:
Code:
[tom@min ~]$ source .bashrc | tee bashteefile
bash: .bashrc: line 162: syntax error near unexpected token `('
bash: .bashrc: line 162: `lf() { ls -F; }'
[ben@min ~]$ cat bashteefile <------Nothing in the file, since the only output is the error!

[tom@min ~]$ source .bashrc 2>&1 | tee bashteefile2
bash: .bashrc: line 162: syntax error near unexpected token `('
bash: .bashrc: line 162: `lf() { ls -F; }'

[tom@min ~]$ cat bashteefile2
bash: .bashrc: line 162: syntax error near unexpected token `('
bash: .bashrc: line 162: `lf() { ls -F; }'

I guess one conclusion about this is to always include the redirection of standard error, as in the article's examples, which will catch all cases. I suppose it depends on what the user wishes to catch in the tee file, just the output, or the errors as well. Notwithstanding that, the catchall approach is the "safest", though it wasn't detailed in the article.
 
Last edited:

Members online


Latest posts

Top