Shell Variables in a cron entry

driesm

Developer
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:

Code:
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
excludes="--exclude=/storage --exclude=/proc"
backupdir="/storage/vados"
#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?
 
Write a script that does all the fancy stuff. Then write the Cron entry to just point to the script. Don't try to do fancy things in the Cron entry, it will break in weird and wonderful ways that will take you days to figure out.
 
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.
 
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.
 
Back
Top