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
If your script file is invoked by
The parent PID is available in bash as variable
but we need the name of the command, not the pid, so we call
now we just need to test the result for "cron"
Now you can test anywhere in your script
Works on FreeBSD or on Linux:
You can go as far up the process tree as you wish.
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
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
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>):