bash脚本产生比由cron执行从shell提示符下执行时不同的结果 [英] Bash script produces different result when executed from shell prompt than executed by cron

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

问题描述

请考虑以下的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?

推荐答案

如图所示<一个href=\"http://stackoverflow.com/questions/18912018/bash-script-produces-different-result-when-executed-from-shell-prompt-than-execu?noredirect=1#comment27919070_18912018\">in该评论,确实使用上的crontab脚本完整路径,因为crontab中确实有比普通用户(在这种情况下,根)不同的环境变量

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

在你的情况,而不是的mdadm / sbin目录/ mdadm的使得它。

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
/bin/rm

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

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