Better Cron env and shell control with the SHELL variable
Published: 08-03-2013 | Author: shtylman | Text only version of this article
Table of Contents
original article from: http://shtylman.com/post/cron-shell-power/ -archived for importance.
If you don't know what cron is this post is not for you.
SHELL variable in cron is more powerful than you may realize.
Most people will have this type of setup in their crontab.
NODE_ENV=productionOTHER_VAR=foo*/10 * * * * /path/to/node /path/to/my/script.js
If you don't want to repeat
/path/to/node (or your runtime) over and over, youwill add a
PATH variable to go with the other variables.
*/10 * * * * /path/to/my/launcher.sh*/10 * * * * /path/to/my/launcher_another.sh
Now you have several shell scripts which invoke the required commands to setupthe environment and then run whatever program.
There is a little known special env variable for cron:
SHELL. Most people knowthis variable can be used to change the shell your scripts run run (i.e.
SHELL=/bin/bash), but it can actually run any file!
So lets say I use nvm and want to setup my environment. Instead of making customlaunchers for each command, I can simply do the following:
SHELL=/path/to/setup/cron.bash*/10 * * * * node $HOME/foo.js
Now lets look at what
cron.bash might look like:
#!/bin/bashset -esource /etc/environmentsource /etc/profile# setup any env variables you want hereexport NODE_ENV=production# I use node so I want to add node path stuff via npm# $HOME is available, but not many other env vars are by defaultsource $HOME/nvm/nvm.sh# restore SHELL env var for cronSHELL=/bin/bash# execute the cron command in an actual shellexec /bin/bash --norc "$@"
For the most part it looks just like any other shell script. The importantmagical parts are the last 4 lines. These lines put back the SHELL variable to
/bin/bash and then execute a bash shell to run the cronline command (the stufffor the specific cronjob).
SHELL=/full/path/to/cron.bashMAILTOfirstname.lastname@example.org# For more information see the manual pages of crontab(5) and cron(8)## m h dom mon dow command# dummy cron command to print the environment variables ever minute* * * * * env# node scripts can simply be run using `node` now* * * * * node /path/to/script/.js
Now our cron files have a consistent environment setup and we can simply runwhatever commands we need without further PATH tricks or nonsense.
Go forth and update your dirty crontabs!bash, cron, env, nodejs, shell, tutorials, zsh