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.