Peter Peter - 1 year ago 51
Bash Question

Bash script produces different result when executed from shell prompt than executed by cron

Please consider following crontab (root):

0 */3 * * * /var/maintenance/

And the bash script


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" "";
echo "ERROR"
echo "ALL OK"


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?

Answer Source

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 which:

$ which rm