1832763 Members
2947 Online
110045 Solutions
New Discussion

Re: Script logging

 
SOLVED
Go to solution

Script logging

When writing a shell script is there a way of directing all output and error to a log without having to add a >> $log to each command?
6 REPLIES 6
Robin Wakefield
Honored Contributor

Re: Script logging

Hi Malcolm,

Can you not redirect the script's output when you run it, e.g.

./my_script.sh >log.out 2>&1

Rgds, Robin.
James Beamish-White
Trusted Contributor

Re: Script logging

An easy way is to call the script from another script which has redirect to one log, or by command line ( #your_script > log 2>&1), or make the 'main' part of the script a function.

Try this:

----------------------------
#!/bin/sh
LOG=/tmp/mylog

your_original_script()
{
...your script...
}

your_original_script >> $LOG 2>&1
----------------------------

Cheers,
James
GARDENOFEDEN> create light
Eugen Cocalea
Respected Contributor

Re: Script logging

Hi,

Yep, run script like:

<script> 1>normal_log 2>error_log

E.
To Live Is To Learn
David Lodge
Trusted Contributor
Solution

Re: Script logging

You can affect the environment for the whole script by using the exec command:

exec 2>&1 >${Logfile}

But, as most shell scripts are run both as batch and by the admin I'd advise using a system that sends output to both the Logfile and stdout - the normal way of doing this is to do summat like:

echo "foo" 2>&1 | tee -a ${Logfile}

This has 2 problems:
* increases size of script
* loses return code of the command before the tee...

What I do is have a function which runs a command, handles the logging and returns the valid return code [it also adds date time and program name to the logfile]:
function LogExec
{
typeset Status
typeset TempFile=$(mktemp)

${@} 2>&1 >${TempFile}
Status=${?}

while read line
do
print "[${1##*/}] $(date "+%Y%m%d %H:%M:%S") ${line}" | tee -a ${LogFile}
done <${TempFile}

rm -f ${TempFile}
return ${Status}
}

So when you have this you just need to do the following:
LogExec rm foo*

instead of
rm foo* | tee -a ${LogFile}

dave
melvyn burnard
Honored Contributor

Re: Script logging

why not take a look at the script command?
man script
My house is the bank's, my money the wife's, But my opinions belong to me, not HP!

Re: Script logging


I tried the script command but found this the best solution.

#!/usr/bin/sh
exec > $log 2>&1

Thanks for the tips.

Malcolm