with a shell script, it is possible to tell when it's run with cron vs run manually?
it was asked why I want to know. My cron job will be logging, and i want to be able to log if someone is executing it manually.
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.Sign up to join this community
In the times that I've needed to do this, i know it's a script that I'll never redirect to a file or to a pipe. So a simple test is to check if stdout (a.k.a file descriptor 1) is a tty (which it won't be from cron). In bash:
if [ -t 1 ] then : # running from terminal else : # not running from terminal, cron maybe fi
Again, warning, this is a test simply if your stdout is a tty. But works for my simple purposes.
You could also check what your parent process is. In Linux, it can be as simple as:
if grep -q cron /proc/$PPID/cmdline &> /dev/null then : # running from cron fi
You could define a unique environment variable in your crontab:
RUNNINGFROMCRON=1 16 18 * * * /usr/local/bin/crontest
I tested with this script:
#! /bin/bash echo " running script " echo -n "testing for var: " echo $RUNNINGFROMCRON
When I ran from
cron output was:
running script testing for var: 1
When I ran from the command line manualy, output was:
running script testing for var:
You can inspect the name of the parent process, which can be retrieved with
ps -p $PPID -o comm=. This is spoofable, of course.
However this is not necessarily a good idea (for example, you won't be able to easily test your cron jobs manually). Maybe if you explain why you want this someone can suggest a better solution.
You could create a special user for the cron job to run under. Then make your script readably by that user only, and put it in the user's crontab. That way, no other user can even read the script, let alone execute it.
BTW, for a secure solution you need to make the cron script unreadable anyway. If other users can read the script, they can copy it, remove whatever cron-check mechanism you have and then run it, bypassing your logging if they want to.