红联Linux门户
Linux帮助

crontab 与 shell 执行结果不一样

发布时间:2011-02-28 10:37:33来源:红联作者:fujiefujie
[i=s] 本帖最后由 fujiefujie 于 2011-2-28 10:38 编辑 [/i]

shell[code]#!/bin/bash
service httpd status &> /dev/null
if [ $? -ne 0 ]
then
day=`date "+%F%R"`
echo "service httpd is down at $day" >> /var/log/htmon.txt
service httpd restart
service httpd status &> /dev/null

if [ $? -ne 0 ]
then
chkconfig --level 2345 httpd on
else
echo "httpd is running now..."
fi
fi[/code]crontab

*/1 * * * * /opt/htmon.sh
文章评论

共有 8 条评论

  1. jelletite 于 2011-03-09 21:38:02发表:

    受教了,一直只用简单的SHELL 工作,少用嵌套,估计还是俺太菜了

  2. Olcevt 于 2011-03-01 08:41:02发表:

    不懂,帮顶个

  3. fujiefujie 于 2011-02-28 13:24:30发表:

    还有一个问题就是用crond执行脚本
    不会显示echo字段信息,该信息已经发到邮箱里。
    要想输出 echo "信息" >> /dev/tty[0]
    方括号里的内容可选。

  4. fujiefujie 于 2011-02-28 12:59:30发表:

    [i=s] 本帖最后由 fujiefujie 于 2011-2-28 13:17 编辑 [/i]

    终于弄明白了,分享一下。
    首先,脚本有错误。脚本中用了if嵌套语句,但该语句的判断内容有重叠。(虽然后来已经启动)所以执行了不同的操作。
    service httpd status &> /dev/null
    if [ $? -ne 0 ]

    service httpd status &> /dev/null
    if [ $? -ne 0 ]

    解决方法:把第二个if语句的判断内容去掉。判断上一个语句的执行情况。

    其次,找不到命令文件。这和crond的环境变量设置有关,直接命令行执行脚本不会报错。
    在crond里提交的脚本是不会读取profile文件的,所以在shell脚本中有必要提供必要的路径和环境变量
    如果crond不能运行脚本,用户会收到一个邮件说明原因。
    解决方案:脚本中加上
    . /etc/profile
    . ~/.bash_profile

  5. fujiefujie 于 2011-02-28 12:08:24发表:

    是环境变量的事儿
    脚本加上 . ~/.bash_profile 和 . /etc/profile
    就能执行了
    可问题是 我的脚本那里出错了 执行时候把服务关了,自启动也off掉。
    怎么会执行 chkconfig --level 2345 httpd on 语句
    郁闷:0w5ty(1

  6. fujiefujie 于 2011-02-28 11:28:09发表:

    是不是crond的环境变量的事儿啊 (5ty(

  7. fujiefujie 于 2011-02-28 11:00:51发表:

    (6)m:b(6)m:b(6)m:b

  8. fujiefujie 于 2011-02-28 10:48:27发表:

    有几个问题请教一下大家:
    @1
    我直接在命令行执行脚本时(已经把httpd服务关掉,自启动也为off)
    脚本可以执行,httpd服务启动了。
    再次执行却没有显示httpd is running now...
    @2
    我用crond服务执行:
    httpd 服务没启开
    提示信息为:
    /opt/htmon.sh: line 11: chkconfig: command not found
    line 7: service: command not found

    是怎么回事儿啊