由Bash执行的脚本与由cron执行的脚本产生不同的结果 [英] Script produces different result when executed by Bash than by cron

查看:109
本文介绍了由Bash执行的脚本与由cron执行的脚本产生不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑使用以下crontab(根):

Please consider following crontab (root):

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

bash脚本/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... "
...

这就是...

...从shell提示(bash)执行:

输出为mdadm --detail /dev/md0的邮件已发送到我的电子邮件中(正常行为)

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

...由cron执行:

空白邮件已发送到我的电子邮件中(主题存在,但没有消息)

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

为什么会有这种差异以及如何解决?

Why such difference and how to fix it?

推荐答案

如评论中所示,请在crontab脚本上使用完整路径,因为crontab确实具有与普通用户(在这种情况下为root)不同的环境变量.

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).

根据您的情况,/sbin/mdadm代替了mdadm.

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

如何获取命令的完整路径?使用命令command -v:

$ command -v rm
/bin/rm

这篇关于由Bash执行的脚本与由cron执行的脚本产生不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆