crontab and binaries in /usr/local/bin

9

I am working in Redhat and have few programs located in folder /usr/local/bin I would like to call from crontab for root user. I thought that by putting binaries in that folder would be sufficient to call the program directly as in the shell.

Essentially I need to specifiy the folder everytime so the crontab below doesn't work

 5 9  * * 1,2,3,4,5 my_bin some_args

but I change it into

 5 9  * * 1,2,3,4,5 source ~/.bashrc; /usr/local/bin/my_bin some_args

Do you know why?

The reason why I sourced bashrc was to add some environment libraries, in particular LD_LIBRARY_PATH as my binary couldn't find some shared libraries from /usr/local/lib.

Abruzzo Forte e Gentile

Posted 2014-07-17T08:09:58.127

Reputation: 1 415

1Probably irrelevant, but still: it's helpful to say the error (it was likely sent by e-mail to the root user), and make sure the files are executable (chmod +x). – Valmiky Arquissandas – 2014-07-19T05:36:46.253

Answers

14

cron jobs run in a very minimal environment, and since they're executed directly by crond without a shell (unless you force one to be created), the regular shell setup never happens. There are two standardish ways to work around this. First, you can define environment variables in your crontab (note that these'll apply to all jobs -- at least, those listed after the definitions):

PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
LD_LIBRARY_PATH=/usr/local/lib

5 9  * * 1,2,3,4,5 my_bin some_args

Second, you can edit the script to be less dependent on its environment (e.g. have it define what it's going to need itself), and then use the full path in the crontab entry:

5 9  * * 1,2,3,4,5 /usr/local/bin/my_bin some_args

Gordon Davisson

Posted 2014-07-17T08:09:58.127

Reputation: 28 538

Hi Gordon! Thank you very much. Essentially I am using the second solution but I really like the first one. – Abruzzo Forte e Gentile – 2014-07-21T07:33:02.487

Typically, /usr/bin programs are available. Is there a reason not to link the program you want (ln -s /usr/local/bin/my_bin /usr/bin/my_bin) so it's available that way? – juacala – 2018-02-03T16:43:00.313

1

@juacala I wouldn't mess up your filesystem organization to work around an oddity of cron. The Filesystem Hierarchy Standard says that locally-installed binaries belong in /usr/local/bin, not /usr/bin; using symlinks doesn't technically violate this, but it certainly violates the intent. Plus it adds another thing to go wrong if you don't keep the symlinks up to date (adding/removing them as programs are added/removed). Plus it doesn't handle binaries in /sbin or /usr/sbin...

– Gordon Davisson – 2018-02-03T20:10:32.300

I decided to do this: 0 0 * * * /bin/bash -l -c "PATH=\"$PATH:/usr/local/bin\"; <your command here>" – ndbroadbent – 2018-07-23T10:05:20.127