I know that there is a possibility to use tee to copy the contents of output to a file and still output it to the console.

However, I can't seem to find a way, to prepare shell scripts (like a fixed template) without using tee for either each command in the script or to execute the script using a pipe to tee.

Thus, I have to start calling the script each time with a pipe to tee instead of automatically doing this for me via the script.

I tried using a modified shebang using a pipe but got no success and I can't seem to find a way to accomplish this.

So instead of calling the script like this:

./myscript.sh |& tee scriptout.txt

I would like to have the same effect just by calling it like this:


Of course the script needs to know the filename which is set in a variable inside the script.

How can I accomplish this?

2 Answers 2


You could wrap the contents of your script in a function and pipe the functions output to tee:


echo "example script"
} | tee -a /logfile.txt


You can probably do something like setting the output at the start of the script using exec. (I haven't tested this very strongly.)


# Split script output to stdout and to the logfile
exec 1> >(tee -a "/tmp/${0##*/}.log")

# Write a message
echo hello, world

# Empirical pause before exiting to wait for all output to get through the tee
sleep 1
exit 0

Example, assuming the script is called demo and has been made executable with chmod a+x demo:

ls -l /tmp/demo.log
ls: cannot access '/tmp/demo.log': No such file or directory

hello, world

cat /tmp/demo.log
hello, world

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .