test if script called by cron

Dan Nelson dnelson at allantgroup.com
Mon Sep 16 12:17:18 UTC 2013


In the last episode (Sep 16), Paul Macdonald said:
> 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.

You check to see if stdin is a terminal, but that's not conclusive.  One way
to know for sure is to look at the name of the process that launched you:

if [ ! -t 0 ] ; then
 echo "no tty, possibly run from cron"
fi

parent=$(ps -o command= -p $PPID)
case $parent in 
 *cron* ) echo "parent is $parent, almost certainly cron" ;;
esac

-- 
	Dan Nelson
	dnelson at allantgroup.com


More information about the freebsd-questions mailing list