Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

I have a fairly simple shell script (foo.sh) that looks like this:

#!/bin/bash
echo -n "$USER,$(date)," `binary -flags | sed -e '1,30d'`;
exit 0;

This script is supposed to prepare some output which will then be appended to a text file, like so:

foo.sh >> data.csv

When I run the above on a root prompt, it works fine. However, when I type the exact same command into my (root) crontab which looks like this:

05 * * * * /root/foo.sh >> /path/to/data.csv

The crontab output differs! I wasn't expecting this and I can't understand why. See examples below:

Expected, normal output from running my .sh (example):
Fri Jun 14 16:32:34 CEST 2013,20130614163304,268828672,71682561

The output written to the file by cron:
Fri Jun 14 16:32:34 CEST 2013,

The rights on the binary run in the .sh looks like this:

-rwxr-xr-x  1 root root

Why does the output differ? How can I get the correct output into my CSV file?

share|improve this question

marked as duplicate by Gilles, slm, Anthon, jasonwryan, rahmu Jun 15 '13 at 9:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2  
specify the full path to binary or add it to PATH in the crontab. –  jordanm Jun 14 '13 at 15:53
add comment

1 Answer

up vote 4 down vote accepted

You can't count on having the same environment in a program run via cron as when you run it interactively. There are two differences most likely to matter in this instance:

  1. The current working directory

  2. The PATH

As jordanm commented above, one or both of these in combination is causing the script to not find your binary program.

If you look at your local system mail (e.g. by running mailx) you will probably find messages complaining about this failure.

It is standard practice when writing crontab entries and scripts intended to be run by cron to hard-code paths to known locations of programs.

share|improve this answer
    
"It is standard practice when writing crontab entries and scripts intended to be run by cron to hard-code paths to known locations of programs." -- thank you, if I had known this, I could have avoided this issue. In this case, I solved it by creating a symlink at /bin/bar instead. By the way, something that helped me troubleshoot the error was appending 2>/root/error.out which showed me the actual error. –  bigbadonk420 Jun 14 '13 at 18:56
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.