test if script called by cron
freebsd at edvax.de
Tue Sep 17 03:38:37 UTC 2013
On Mon, 16 Sep 2013 23:28:17 -0400, kpneal at pobox.com wrote:
> On Mon, Sep 16, 2013 at 02:05:04PM +0200, Polytropon wrote:
> > On Mon, 16 Sep 2013 12:26:59 +0100, Paul Macdonald wrote:
> > > Is there a simple way of testing whether a given script was called via cron,
> > >
> > > I'd rather find a solution that would work from within the script rather
> > > than setting an environment variable in the crontab.
> > I'd suggest the script creates a file (lock file or,
> > much easier, just a simple normal file) at its beginning:
> > #!/bin/sh
> > /usr/bin/touch /tmp/scriptrun
> > # ... your script content here ...
> Wouldn't the lockf command be better than touch? That way you get the
> condition code telling you whether or not the script is already running.
Yes, it would probably be better in this case. This, in
combination with the suggestion of "test-t 0" to check
if the script has been interactively called or not, looks
like a better solution.
However, the intial question does not make fully sure (at
least to me as a non-native speaker) if the intention is
(a) to check _if_ the script has been run via cron, or
(b) to check if the script has been run via _cron_. :-)
> > Of course you would have to manually remove that file
> > after you have verified its existence and content.
> If you use lockf as a drop-in replacement for touch then, yes, you'll
> need to keep the lock file until removing it at the end of the script.
Depends. Let's say the script is scheduled at 3:00 and will
finish in about half an hour. The "evidence file" will only
be visible from 3:00 to ca. 3:30, so removing the "evidence
file" after the script has finished could lead to a false-negative
result ("has not been run"). This is also true for the more
simple solution using the touch command (no rm call at the
end of the script).
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...
More information about the freebsd-questions