1821245 Members
3060 Online
109632 Solutions
New Discussion юеВ

cron stdout redirection

 
SOLVED
Go to solution
Glenn L. Stewart
Frequent Advisor

cron stdout redirection

Hi All,

My crontab's are terribly messy at the moment. On one of the HA boxes (using MC
Service Guard) had each and every crontab entry testing whether it was on the
functioning portion of the cluster before running. This lead to crontab entries
that were as long as 4-5 lines long.
A wrapper script brought this back to a single line.

Nearly every script we use has stdout though and so is typically redirected to
a log or /dev/null 2>&1.

I am trying to figure out how I can simply implement into any script an easy
way to determine if it is running from cron or not (easy task), and therefore
either output to stdout OR output stdout/stderr to a logfile within the first
few lines of the script (harder task).

A simple test, running /usr/bin/tty and determining exit code, shows whether a
script is running from cron/at or from elsewhere.
On top of this though, now I want to be able to redirect all stdout to a log if
running from cron.
For example:

LOGFILE=/tmp/$0.log
if /usr/bin/tty > /dev/null 2>&1
then
# Not running from Cron or AT
CRON=N
else
# Running from Cron or AT
CRON=Y
# insert line here to redirect all further output to $LOGFILE
fi

Any quick fix... or is another Wrapper script/function needed?

The other admin here has recommended putting the entire script+functions into
one larger function encompassing the entire script contents.
I'm sure there is a better solution.

Not only will this make the crontab neater, but in recent scripts I have
decided to automate log trimming. That's fine for logs created internally, but
not helpful for logs of all script output. The crontab entry determines where
everything is logged
E.g. - crontab entry
/dir/script >> /dir/logfile 2>&1
In this case, the name of the logfile can be changed. The script cannot
determine it is having output logged (of course listing crontab and grepping
for $0 might work, but quite messy - could also have numours entries with
identical $0)



Glenn

2 REPLIES 2
Glenn L. Stewart
Frequent Advisor

Re: cron stdout redirection

Answered my own question.

Solution: exec>logfile 2>&1
James R. Ferguson
Acclaimed Contributor
Solution

Re: cron stdout redirection

Hi Glenn:

You can determine whether or not your script is interactive (i.e. not launched as a 'cron task) by adding this test:

if [ -t -eq 0 ]
then
echo "interactive - not cronned"
fi

An easy way to redirect all output (e.g. both stdout and stderr) to a log file without specifying redirecton on every 'echo' or 'print' statement is to do this:

exec 2>&1 >> /tmp/mylog

In your case you might do:

if [ -t -ne 0 ]
then
exec 2>&1 >> /tmp/mylog
fi

Regards!

...JRF...