18

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
  • 1,725
  • 5
  • 17
  • 21
  • 1
    Probably 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 Jul 19 '14 at 05:36

1 Answers1

30

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
  • 34,084
  • 5
  • 66
  • 70
  • Hi Gordon! Thank you very much. Essentially I am using the second solution but I really like the first one. – Abruzzo Forte e Gentile Jul 21 '14 at 07:33
  • 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 Feb 03 '18 at 16:43
  • 1
    @juacala I wouldn't mess up your filesystem organization to work around an oddity of cron. The [Filesystem Hierarchy Standard](http://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch04s09.html) 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 Feb 03 '18 at 20:10
  • 2
    I decided to do this: `0 0 * * * /bin/bash -l -c "PATH=\"$PATH:/usr/local/bin\"; "` – ndbroadbent Jul 23 '18 at 10:05
  • 2
    Just a side note: `$PATH` only contains `/usr/bin:/bin` in cronjobs on Ubuntu – Michele Locati Jul 14 '21 at 16:14