Is there any variable that cron set when it's running a program ? If the script is running by cron, I'll skip some parts; otherwise invoke those parts.
How can I know if the bash script is started by cron ?
|
I'm not aware that 1) Make a hard link to the script file, so that, for example, 2) Add an option to the script, and set that option in the crontab invocation. For example, add an option And of course, cron can set arbitrary environment variables, so you could just put a line like |
|||
|
|
|
First, get cron's PID, then get the current process's parent PID (PPID), and compare them:
If your script is started by another process that might have been started by cron, then you can walk your way back up the parent PIDs until you get to either $CRONPID or 1 (init's PID). something like this, maybe (Untested-But-It-Might-Work<TM>):
|
|||
|
|
|
Scripts run from cron are not run in interactive shells. Neither are startup scripts. The differentiation is that interactive shells have STDIN and STDOUT attached to a tty. Method 1: check if
Method 2: check is
reference: http://theory.uwinnipeg.ca/localfiles/infofiles/bash/bashref_54.html Method 3: test your tty. it's not as reliable, but for simple cron jobs you should be ok, as cron does not by default allocate a tty to a script.
Keep in mind that you can however force an interactive shell using |
|||
|
|
|
Works on FreeBSD or on Linux:
You can go as far up the process tree as you wish. |
|||
|
|
ps? – terdon Aug 31 '12 at 9:20psis fairly badly documented (especially Linux's version which supports several different syntax styles) and the man page is even more dense and cryptic than most tools. I suspect most people don't even realise just how useful and versatile a toolpscan be. – Craig Sanders Aug 31 '12 at 12:55