Thursday, February 23, 2012

Environment Friendly Cron Shell Scripts

You created a neat shell script which makes use of some environment variables and all the tests went successful. But as soon as the script is scheduled in crontab; none of the environment variables were recognized and script fails.

Since crontab is executed as a different user in UNIX so assuming that your environment variables defined in $HOME/.profile will be available to any other user is wrong.

A simple solution is to execute the environment variables at the beginning, just after where you define the shell, of the script:

. /home/user/.profile

where /home/user is the absolute path of your $HOME variable.

This should get you going.

TIP: Also using following export and assignation in a single line causes issues with shell scripts so make sure that
is replaced by
export MY_VAR

Otherwise errors in your .profile file may cause issues with your shell script. All the best!!!

No comments:

Post a Comment