Home > cron, linux tips > Easy way to fix script errors that occur when scheduled with cron

Easy way to fix script errors that occur when scheduled with cron

Some scripts that work fine when run manually in a shell environment will just fail when scheduled with cron. This is due to shell environment variables not available to those scripts when cron executes the scripts. You can verify this by running env or printenv commands in both the shell in which you manually execute the script and in cron by schedule it to the nearest minute and writing it to a file.

# m h  dom mon dow   command
35 * * * * env > /tmp/env.log

By comparing both outputs you can find that the environment variables available in cron are very limited.

Most errors will arise due to commands in your script not available in location set by cron environment PATH variable. You can compare the value of PATH variable in both outputs and tell that the executable paths cron looks in is very limited. You can fix this by giving the full path to commands in your shell script, but you have to look for where the executables are located and modify all those scheduled scripts.

However there is one easy fix to this problem. The important thing to note is cron allows you to set environment variables in the crontab file. So you could just add the variables you wanted to be available to cron at the top of the crontab file as shown below.

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# m h  dom mon dow   command
38 * * * * env > /tmp/env.log

Now schedule the script again and check the output of /tmp/env.log file. You can see that the values you passed were availabe to cron. By this way you can run those scripts just the way it is without any modifications.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: