Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: interactive vs cron called



> Is there a way to tell if a script is being called by cron or via
> interactive script?  I'm writing something to tell me when disk usage of
> various partitions get's to dangerous levels.  When it's run via cron, I
> want it to mail me the results.  If it's interactive, I want it to print
> the output to the screen.

A rather complex solution, but should work nonetheless.  Find the parent 
process of the script (ie, parent of $$) and then put a name to it.  If the 
parent is /usr/sbin/cron, it's cron invoked, else its interactive.  I'm not 
100% sure if parent process would be the shell (e.g. /usr/local/bin/zsh) but 
you could probably get it's parent process.

How about:

PPID=`ps -Al | nawk -v pid=$$ '{ if ( $4 == pid ) print $5 }'`
PPNAME=`ps -Al | nawk -v ppid=$PPID '{ if ( $4 == ppid ) print $14 }'`

Do a check on PPNAME, et voila!

>From a quick test, if invoked via interactive script, it returns 'zsh' (ie, 
the shell).  If invoked via crontab, it returns 'sh' (since crontab invokes 
everything under /bin/sh).  If you take it a step up, the interactive shell 
will return xxxx (for me it's currently dtterm) and the crontab will return 
cron.  So:

PPID=`ps -Al | nawk -v pid=$$ '{ if ( $4 == pid ) print $5 }'`
PPPID=`ps -Al | nawk -v ppid=$PPID '{ if ( $4 == ppid ) print $5 }'`
PPPNAME=`ps -Al | nawk -v pppid=$PPPID '{ if ( $4 == pppid ) print $14 }'`

and now PPPNAME will be the name of the parent of the parent of the current 
process.

NB: from a quick check on ps -Al, the 11th field doesn't seem to always print; 
I believe off the top of my head there's a way to check the last field which 
would circumvent this.

--
John Riddoch			Programmer/Webmaster
Room C6, School of Computer and Mathematical Science
Robert Gordon University, Aberdeen, AB25 1HG
Telphone: (01224)262721
Email jr@xxxxxxxxxxxxxx



Messages sorted by: Reverse Date, Date, Thread, Author