5

Please consider following crontab (root):

SHELL=/bin/bash
...
...
0 */3 * * * /var/maintenance/raid.sh

And the bash script /var/maintenance/raid.sh:

#!/bin/bash

echo -n "Checking /dev/md0... "
if ! [ $(mdadm --detail /dev/md0 | grep -c "active sync") -eq 2 ]; then
    mdadm --detail /dev/md0 | mail -s "Raid problem /dev/md0" "my@email.com";
    echo "ERROR"
else 
    echo "ALL OK"
fi;

#-------------------------------------------------------

echo -n "Checking /dev/md1... "
...

And this is what happen when...

...executed from shell prompt (bash):

Mail with mdadm --detail /dev/md0 output is sent to my email (proper behaviour)

...executed by cron:

Blank mail is sent to my email (subject is there, but there is no message)


Why such difference and how to fix it?

jww
  • 97,681
  • 90
  • 411
  • 885
Peter
  • 16,453
  • 8
  • 51
  • 77

3 Answers3

5

As indicated in the comments, do use full paths on crontab scripts, because crontab does have different environment variables than the normal user (root in this case).

In your case, instead of mdadm, /sbin/mdadm makes it.

How to get the full path of a command? Using the command command -v:

$ command -v rm
/bin/rm
jww
  • 97,681
  • 90
  • 411
  • 885
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    If the command is not already in a directory listed in `PATH`, `which` will not find it for you. – chepner Sep 20 '13 at 16:28
3

cron tasks run in a shell that is started without your login scripts being run, which set up paths, environment variables etc.

When building cron tasks, prefer things like absolute paths and explicit options etc

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Bohemian
  • 412,405
  • 93
  • 575
  • 722
3

Before running your script as a cron job, you can test it with no environment variables using env -i

env -i /var/maintenance/raid.sh
Cole Tierney
  • 9,571
  • 1
  • 27
  • 35
  • 2
    `cron` jobs are usually executed as a different user than when the script is developed. It seems like you would need something like `env -u root -i /var/maintenance/raid.sh` to accurately test it. – jww Jun 02 '19 at 01:10