with a shell script, it is possible to tell when it's run with cron vs run manually?
with a shell script, it is possible to tell when it's run with cron vs run manually?
UPDATE:
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.
Solution 1:
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
Solution 2:
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:
Solution 3:
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.