1833053 Members
2478 Online
110049 Solutions
New Discussion

Re: Cron

 
SOLVED
Go to solution
Jose Mosquera
Honored Contributor

Cron

I need to differ when a script is executed by the cron. How can I identify inside a script that the cron is who executes it?

Rgds.
6 REPLIES 6
Pete Randall
Outstanding Contributor

Re: Cron

Have cron invoke a wrapper script which sets the FROMCRON variable and then calls the common script.


Pete

Pete
Peter Godron
Honored Contributor

Re: Cron

Hi,
variation on Pete's suggestion:

Modify the actual cron call:

05 12 * * * export FROMCRON="cron";/a.sh > /a.lis 2>&1
john korterman
Honored Contributor
Solution

Re: Cron

Hi Jose,

I tried to insert this at the beginning of a script:

#!/usr/bin/sh

PARENT=$(UNIX95= ps -ef | grep $PPID | awk -v ppid=$PPID '$2 ~ ppid {print $3}')

CRON=$(UNIX95= ps -C cron | grep -v CMD| awk '{print $1}')

if [ $PARENT = $CRON ]
then
echo executed by cron
else
echo not executed by cron
fi

It seems to work on my system, but may not work anywhere else!


regards,
John K.

it would be nice if you always got a second chance
A. Clay Stephenson
Acclaimed Contributor

Re: Cron

Two ways immediately suggest themselves:

1) Link (hard) the normal version of the script and a cron version of the script.

e.g. normalscript.sh crnvrsionXY123.sh

Now your code simply tests ${0} to see which name was used to invoke the script.
Note that you intentionally make the cron'ed name difficult to use by including
deliberately obtuse characters.

2) Test stdin to see if it is a TTY device (ie, a terminal)

if [ -t 0 ]
then
echo "Interactive"
else
echo "Non-interactive; probably cron"
fi


If it ain't broke, I can fix that.
spex
Honored Contributor

Re: Cron

Jose,

I found this on the forums some time ago:

typeset INTERACTIVE=0 && [ -t 0 ] && INTERACTIVE=1

Put it in the beginning of the script to be executed, and then test 'INTERACTIVE'.

PCS

Jose Mosquera
Honored Contributor

Re: Cron

Thank you very much!