Written by James McDonald

October 22, 2011

It works from the command line. Why doesn’t it work in Cron?

…insert head scratching here…

Firstly run your cron job often so you can get some output. Use common sense here, obviously if the cron scripts takes 5 minutes to run then you would bump up the frequency to 6 minutes. If it runs in a few seconds then every minute is fine.

Example of a cron script running every 5 minutes and one minute

# use the crontab -e command to edit your command
# or install gnome-schedule for a gui cron editor

# every 5 minutes
*/5 * * * * /path/to/your/script.sh
# every minute
*/1 * * * * /path/to/your/script.sh

Next you want both standard out (STDOUT) and your standard error (STDERR) directed to somewhere handy. In this case I’ve chosen my tmp directory and file named out
Example of redirecting cron STDOUT/STDERR script output to a file
Check the contents of /tmp/out for any errors and fix them.

*/1 * * * * /path/to/your/script.sh >/tmp/out 2>&1

Sometimes the environment available to cron is a lot more limited than to a normal user sessions especially the PATH variable. Perhaps your script is calling programs that are not in the cron jobs PATH.

It’s good practice to put the full path to all programs you call from a cron script just in case the program isn’t in PATH

Example of setting up your cron script to check the PATH and environment

# use which command to locate env
which env
# copy and paste this into your script
# find each program you are going to use
which echo

# edit your script thusly
vi /path/to/your/script.sh

# specify full path to you program
$ECHO Sending Environment to a file
$ENV > /tmp/myenv

Example contents of /tmp/myenv
Notice that /usr/local/bin, /home/me/bin, /sbin and /usr/sbin isn’t in the path used by a normal cron user.


Also check the contents of your cron logs

# use sudo or su to root to read the log
sudo vi /var/log/cron
Oct 22 18:01:01 llbb run-parts(/etc/cron.hourly)[17028]: finished mcelog.cron
Oct 22 18:10:01 llbb /USR/SBIN/CROND[17111]: (username) CMD (/path/to/your/script.sh >/tmp/out 2>&1)

Finally for program specific help use Google to get information on your troubles.


Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…

List local disks

GET-CimInstance -query "SELECT * from Win32_DiskDrive" DeviceID Caption Partitions Size Model -------- -------...

Create ISO using Powershell

Usage New-IsoFile -NewIsoFilePath C:\tmp\Hyper-V.iso-sources -ImageName Hyper-V -SourceFilePath 'C:\tmp\Hyper-V'...