Bash – Check if Script is Started by Cron or Manually Invoked

bashcronscriptingshell

Is there any variable that cron sets when it runs a program ? If the script is run by cron, I would like to skip some parts; otherwise invoke those parts.

How can I know if the Bash script is started by cron ?

Best Answer

I'm not aware that cron does anything to its environment by default that can be of use here, but there are a couple of things you could do to get the desired effect.

1) Make a hard or soft link to the script file, so that, for example, myscript and myscript_via_cron point to the same file. You can then test the value of $0 inside the script when you want to conditionally run or omit certain parts of the code. Put the appropriate name in your crontab, and you're set.

2) Add an option to the script, and set that option in the crontab invocation. For example, add an option -c, which tells the script to run or omit the appropriate parts of the code, and add -c to the command name in your crontab.

And of course, cron can set arbitrary environment variables, so you could just put a line like RUN_BY_CRON="TRUE" in your crontab, and check its value in your script.

Related Question