Skip to main content Logo (IEC resistor symbol)logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

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: -archived for importance.

If you like this article, consider sponsoring me by trying out a Digital OceanVPS. With this link you'll get $100 credit for 60 days). (referral link)

If you don't know what cron is this post is not for you.

Using the SHELL variable in cron is more powerful than you may realize.

typical crontab

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.

But what happens if you want to use something like nvm or rvm orvirtualenv, etc? It is not uncommon to have the above change to somethinglike the following

*/10 * * * * /path/to/my/*/10 * * * * /path/to/my/

Now you have several shell scripts which invoke the required commands to setupthe environment and then run whatever program.

enter SHELL

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/ 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/ 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!

- home -

Tags: bash, cron, env, nodejs, shell, tutorials, zsh