I already have implemented a way to identify if a script is running from a cron job. It uses ps
to clim up the process tree and identify if any (recursive) parent command contains "cron" or "CRON".
This solution, while working, is slow (say, around one second) and impacts all the scripts I have, every time I call them. I am looking for a faster solution.
I do not want to add any option to the script inside the crontab, as my goal is precisely to define default notification behavior when no notification option is provided on the command line, and have that default behavior different for cron jobs.
Is there a reasonably reliable, fast way to find out if the script (or one of its recursive parents) was launched from a cron job?
After my initial post, I have reworked my code and been able to improve it, though ps
is still used. The code is below, any suggestion is welcome.
is_cron_job()
{
local PS
local CMD
local PID=$$
while :
do
PS="$(ps -h -o ppid,comm -p $PID)"
[[ "$PS" =~ ^[[:space:]]*([0-9]+)[[:space:]]+(.*)$ ]] || return 1
PID="${BASH_REMATCH[1]}"
[[ "$PID" -ge 1 ]] || return 1
CMD="${BASH_REMATCH[2]}"
! [[ "$CMD" =~ crond|CROND ]] || return 0
done
return 1
}