Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force `tee` to run for every command in a shell script?

I would like to have a script wherein all commands are tee'd to a log file.

Right now I am running every command in the script thusly:

<command> | tee -a $LOGFILE

Is there a way to force every command in a shell script to pipe to tee?

I cannot force users to add appropriate teeing when running the script, and want to ensure it logs properly even if the calling user doesn't add a logging call of their own.

like image 341
warren Avatar asked Nov 28 '22 19:11

warren


2 Answers

You can do a wrapper inside your script:

#!/bin/bash
{
echo 'hello'
some_more_commands
echo 'goodbye'
} | tee -a /path/to/logfile

Edit:

Here's another way:

#!/bin/bash
exec > >(tee -a /path/to/logfile)
echo 'hello'
some_more_commands
echo 'goodbye'
like image 171
Dennis Williamson Avatar answered Dec 01 '22 10:12

Dennis Williamson


Why not expose a wrapper that's simply:

/path/to/yourOriginalScript.sh | tee -a $LOGFILE

Your users should not execute (nor even know about) yourOriginalScript.sh.

like image 35
Vinko Vrsalovic Avatar answered Dec 01 '22 09:12

Vinko Vrsalovic