One of the problems running shell (ksh/bash) scripts under cron is suddenly finding that your brilliant script no longer behaves the same under cron as it did from the shell.
There are a number of causes of this and the most common are usually caused by incorrect assumptions about the environment the script will run in.
When writing a script to run under cron the PATH may be different from your PATH in your shell. Always set an explicit PATH at the beginning of the shell script.
e.g.
PATH=/usr/bin:/usr/local/bin
You can use export at the start of the line if you want, but cron will export a default PATH to begin with, meaning that you just need to change the value of it. On Solaris you may need to set the various paths for loading of dynamic libraries, if this is applicable.
Further (and sometimes fatal) problems will arise if you have environment variables in your shell environment that do not exist at all when running under cron.
Consider this scenario in your script:
cd $TMP; rm -rf *
On older systems that use / as the home directory for root this can cause the entire filesystem tree to be deleted if TMP is not defined - something I have seen happen because of this exact problem in someone's startup script. It is always a good idea for root to have its own home directory and not use / itself.
Always set the following option in your shell scripts:
set -u
This will cause the expansion of an undefined variable to halt execution of the program.
By the way, both of these techniques should be used in all your scripts, regardless of whether they are to be run from the command line or cron. Remember, the scripts you write may also be run by someone else and in these cases the environment may be sufficiently different to cause problems.
No comments:
Post a Comment