2

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?

1
  • 2
    specify the full path to binary or add it to PATH in the crontab.
    – jordanm
    Commented Jun 14, 2013 at 15:53

1 Answer 1

3

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.

1
  • "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.
    – pzkpfw
    Commented Jun 14, 2013 at 18:56

Not the answer you're looking for? Browse other questions tagged .