Help with implementing logging

I'm trying to add logging to an existing script which echos a number of lines to the screen. I've added a switch to the script that is going to suppress much of this output and put it in a file instead.

The way I envisioned it was like this:

$log would be set to either "" or the log files redirection

log=">> ./tstlogfile.txt"

echo "Text to terminal"

echo "text to log file" $log

I thought this would work, but it takes my redirection string literally... is there an easy way of doing this that I'm missing?

try

LOGFILE=`./tstlogfile.txt`
echo "text to terminal"
echo "text to logfile">> $LOGFILE

Yeah, I thought of that, but it would error when logging wasn't on because logfile would be empty.

Log file will not become empty, as this is not redirection (>), that is append operation (>>).

This (slightly edited) code works on our HP-UX machine.

LOGFILE=$LOGDIR/tstlogfile.txt
echo "text to terminal"
echo "text to logfile" >> $LOGFILE

I meant the variable $LOGFILE would be empty which would error when the line gets interpreted as:

echo "text to logfile" >> 

You'd get an error:

syntax error: `newline or ;' unexpected

If your script doesn't use terminal for other purposes than logging, you can use exec
See tuto here Using exec
See example 19.2

Ah, yes. This looks like it will do the trick... thanks.

if you have tee command then you can do it like..

LOGFILE='./tstlogfile.txt'
echo "text to both terminal and log file" | tee -a $LOGFILE