zoukankan      html  css  js  c++  java
  • 脚本在Shell可以执行成功,放到crontab里执行失败

    一、背景

    自己写了个监控MGR状态的脚本,直接在Linux的Shell环境下可以执行成功,但是只要放到crontab里执行,就失败,脚本内容如下

    #!/bin/bash
    
    MAIL_ADDR=`cat /data/mysql_monitor/m.conf |grep mailaddress |cut -d ":" -f2`
    USER=`cat /data/mysql_monitor/m.conf |grep mysql_user |cut -d ":" -f2`
    PASSWORD=`cat /data/mysql_monitor/m.conf |grep mysql_pwd |cut -d ":" -f2`
    MYSQL_STAT_LOG=`cat /data/mysql_monitor/m.conf |grep mysql_stat |cut -d ":" -f2`
    
    IP=`cat /data/mysql_monitor/m.conf |grep ip |cut -d ":" -f2`
    MYSQL_PORT=`netstat -na|grep "LISTEN"|grep -w "3306"|awk -F[:" "]+ '{print $4}'`
    DATE=$(date "+%Y-%m-%d %H:%M.%S")
    
    #Check_status(){
    STATUS=$(mysql -u$USER -p$PASSWORD --connect_timeout=5 -e "SELECT * FROM performance_schema.replication_group_members;" 2>&1 |sed -n '/group_replication_applier/p' |grep -w "ONLINE")
    
    MGR=`echo $STATUS |grep ONLINE |awk '{print $5}' |head -n 1`
    if [ "$MGR" = "ONLINE" ]
    then
        echo "MySQL MGR is ONLINE" > $MYSQL_STAT_LOG
    else
        echo "$DATE Server: $IP MySQL MGR status is not ONLINE,Please check MGR status!" > $MYSQL_STAT_LOG
        python /data/mysql_monitor/mail.py 'mysql' $MAIL_ADDR  "$IP Mysql Warn"  < $MYSQL_STAT_LOG
    fi
    

    二、排查思路

    一般这种情况都是由于环境变量没有获取到导致(所以为什么很多脚本里都会有一行export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin),可能包括脚本定义的环境变量,和系统本身的环境变量

    脚本里定义的环境变量没有获取到

    在脚本里引用的每个变量下一行,都加上echo $变量名并追加到文件中,例如:

    # echo $MYSQL_USER >> /tmp/test
    

    将脚本放到crontab中,然后观察/tmp/test,看看是哪一个变量没有获取到

    2.1系统环境变量没有获取到

    比如我这次要用mysql命令,那么先查出mysql命令在哪里

    # which mysql
    /usr/local/mysql/bin/mysql
    

    查看crontab执行的环境变量

    [root@oratest52 mysql_monitor]# cat /etc/crontab 
    SHELL=/bin/bash
    PATH=/sbin:/bin:/usr/sbin:/usr/bin
    MAILTO=root
    
    [root@oratest52 mysql_monitor]# echo $PATH
    /usr/local/mysql/bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
    

    可以发现cron的环境变量少了/usr/local/bin,/usr/local/sbin,/root/bin,/usr/local/mysql/bin/

    三、解决办法

    在脚本里加入一行

    export PATH=/usr/local/mysql/bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
    

    在我这个案例里,也可以在脚本执行mysql时用绝对路径

    /usr/local/mysql/bin/mysql
    

    可见在我们写脚本的时候,命令路径最好是用绝对路径,如果脚本用到一些非系统自带的命令,最好是在脚本里声明$PATH

    WilliamZheng©版权所有 转载请注明出处! 运维架构师群:833329925
  • 相关阅读:
    How to function call using 'this' inside forEach loop
    jquery.validate.unobtrusive not working with dynamic injected elements
    Difference between jQuery.extend and jQuery.fn.extend?
    Methods, Computed, and Watchers in Vue.js
    Caution using watchers for objects in Vue
    How to Watch Deep Data Structures in Vue (Arrays and Objects)
    Page: DOMContentLoaded, load, beforeunload, unload
    linux bridge
    linux bridge
    EVE-NG网卡桥接
  • 原文地址:https://www.cnblogs.com/williamzheng/p/11364342.html
Copyright © 2011-2022 走看看