9

I'm familiar with using tee, and I know that I can simply log output with

script.sh | tee file.log

However, I want a seamless interface for the user. Is there a way to, within script.sh, run tee as if it was being done as above? Within this script there are hundreds of echoes and lots of other scripts being run, it would be difficult to individually append each to file.

1 Answers1

12

Solution 1: exec

You may place an exec command at the beginning of the script:

$ cat script1
#!/bin/bash
exec > >(tee file.log)
echo one
echo two

Here is an example of running script1:

$ bash script1
$ one
two

$

Observe that the shell prompt returned before the output from the script was complete. This is because the output went to a subprocess and, due to vagaries of multitasking, it completes on its own schedule. For this reason, I prefer the second solution shown below:

Solution 2: grouping

You can put the entire script in a shell group, {...}, and then redirect output from the group:

$ cat script2
#!/bin/bash
{
echo one
echo two
} | tee file.log

This can be done for arbitrarily complex scripts. Just put { at the beginning and } | tee file.log at the end.

A sample run looks like:

$ bash script2
one
two
$ 

Notice that the output neatly completes before the prompt returns.

John1024
  • 17,343