crontab不生效

背景:不知道什么原因脚本手动执行:正常;crontab执行不生效;

 

总结原因:

1.shell脚本中绝对路径问题(尤其是生成文件路径)

2.crontab的环境变量问题(尤其是命令调用路径)

 

用下面的脚本解析以上两个问题:

----------------------------------------------------------

[root@monitor2 scripts]# cat cron.sh 
#!/bin/sh# func : 远程登录MySQL执行SQL语句,返回结果导入日期结尾的文件,每分钟执行一次脚本
user='admin'
pswd='admin'
host='10.10.60.108'
port=4001
MYSQL_CMD="mysql -u${user} -p${pswd} -h${host} -P${port}"     # 远程登录命令,直接调用mysql命令。
SQL="SELECT VERSION();"
time_mark=`date '+%Y%m%f%H%M%S'`
#filedir="/data/scripts"     # 生成文件的绝对路径
filename="version_${time_mark}.txt"     # 直接指定文件名字
${MYSQL_CMD} -e"${SQL}" >${filename}     # 直接写入指定的文件中 取决于上面filename变量

--------------------------------------------------------

以上是脚本内容!!!

--------------------------------------------------------

计划任务:

*/1 * * * * /bin/sh /data/scripts/cron.sh

--------------------------------------------------------

 

解析问题:

【shell脚本中绝对路径问题】

1.在脚本所在目录下:/data/scripts/手动执行以上脚本(不是绝对路径文件)

命令:./cron.sh

结果:正常生成文件

-rw-r--r--. 1 root root       26 Jan 10 12:13 version_20170110121326.txt

-rw-r--r--. 1 root root       26 Jan 10 12:13 version_20170110121344.txt

2.crontab执行脚本

观察:

[root@monitor2 scripts]# tailf /var/log/cron

Jan 10 12:17:01 monitor2 CROND[524]: (root) CMD (/bin/sh /data/scripts/cron.sh)

结果:计划任务照常执行,但是不会生成文件

3.修改脚本,生成文件是绝对路径

脚本:

filedir="/data/scripts"     # 生成文件的绝对路径:开启
filename="${filedir}/version_${time_mark}.txt"     # 直接指定文件名字:绝对路径了

运行:手动执行,正常生成文件

运行:计划任务运行,正常生成文件

 

【crontab的环境变量问题】

1.脚本中:直接使用mysql命令

命令:手动执行脚本,正常输出文件。因为:/etc/profile 中加入 了系统环境变量:/usr/local/mysql/bin/

2.crontab执行:如果想成功执行

分两种情况:

     1.脚本中mysql命令指定绝对路径:/usr/local/mysql/bin/mysql

     2.将mysql可执行文件复制到:crontab的环境变量指定的路径中

 

------------------------------------------------------
# crontab的配置文件!!!
------------------------------------------------------
[root@monitor2 scripts]# cat /etc/crontab 
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin     # 将mysql可执行文件复制到/usr/bin下,脚本中就可以直接使用mysql命令
MAILTO=root
HOME=/# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed-------------------------------------------------------------

!查看:cron的log日志文件:

  tailf /var/log/cron

 

!重启crond服务:

  service crond restart

 

总结:

脚本中涉及文件和命令的使用最好都用上绝对路径!!!

脚本中涉及文件和命令的使用最好都用上绝对路径!!!

脚本中涉及文件和命令的使用最好都用上绝对路径!!!

--------------------------------------------------------------

远方不一定有诗,但有更好的自己!你我共勉!