• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Shell Variables in a cron entry



Thanks: 12
Messages: 44

I'd like to define some local variables in a cron entry so that I can create the following file /usr/local/etc/cron.d/rsync with the following contents:

excludes="--exclude=/storage --exclude=/proc"
#minute    hour mday month   wday    user    command
0              *        *         *            *           root    rsync -a $excludes / $backupdir --delete
Will this work for the "excludes" and "backupdir" variable or can only environmental variables be set this way?



Thanks: 566
Best answers: 3
Messages: 1,015

I actually take Phoenix' advice and turn it into a dogma.

Cron only calls scripts. They all live in /usr/local/sbin, and their names always start with "do...", like "do_hourly_backup". Those scripts take other programs, and wrap them into a cron-friendly package: Something that either fails or succeeds, doesn't output any garbage on stdout or stderr (but leaves logs in well-known places), and in case of failure outputs a very concise and clear message.

Like that all the variables, settings, and error handling is kept away from cron. Cron has a simple job: start scripts at the same time; the scripts know how to take care of themselves.



Thanks: 1,090
Best answers: 2
Messages: 2,398

The one thing I don't quite understand: if you're unsure of something, why not give it a try? :) Log on as regular user, then a mere crontab -e is enough to set up a testcase. The reason I mention this is because it's basically the best way to learn about this stuff.

Well.. that and crontab(5) of course ;)

Will this work for the "excludes" and "backupdir" variable or can only environmental variables be set this way?
Only environment variables can be set within a crontab and what you set up should indeed work without problems. This is just the way environment variables usually behave.

But I definitely agree with the others: this has the potential to only cause issues overtime. What if you need to change those settings at some point? Editing and re-installing a new crontab is a lot more intrusive than merely editing a script. Use cron to fire up your backup script, then put all the logic you need in the script.