[CentOS] 解决 crontab 无法读取环境变量的问题

1. 问题描述

一段数据处理的 shell 程序,在 shell 中手动运行,可以正确执行。但是,把它放在 crontab 列表里,就会报错,提示 "matlab: command not found."。

AutoRefreshData.sh 的部分内容如下:

[She@She ~]$ cat /home/She/data/AutoRefreshData.sh
#!/bin/bash
...
MatlabFile='/mnt/L/Data/main4mat.m'
chmod +x ${MatlabFile}
matlab  -nodesktop -nosplash -nojvm < ${MatlabFile} 1>running.log 2>running.err &

在终端下,AutoRefreshData.sh 可正确执行:

[She@She ~]$ /home/She/data/AutoRefreshData.sh
[She@She ~]$ cat ~/running.log

 < M A T L A B (R) >
 copyright 1984-2015 The MathWorks,Inc.
 R2015b (8.6.0.267246) 64-bit (glnxa64)
 August 20,2015


For online documentation,see http://www.mathworks.com/support
For product information,visit www.mathworks.com.

>> >> >> >> >> >> >> /mnt/L/Data/matFile/jpl16228.mat
>> 
[She@She ~]$ cat ~/running.err
[She@She ~]$ 

将该 shell 脚本添加到 crontab 中:

[She@She ~]$ crontab -l
# part 2: refresh She data from FTP
08 12 * * * /home/She/data/AutoRefreshData.sh > /dev/null 2>&1

在 crontab 中,运行报错,结果如下:

[She@She ~]$ cat ~/running.log
[She@She ~]$ cat ~/running.err
/home/She/data/AutoRefreshData.sh: line 111: matlab: command not found 

2. Bug 原因分析与修复

原因分析:crontab 有一个坏毛病, 就是它总是不会缺省的从用户 profile 文件中读取环境变量参数,经常导致在手工执行某个脚本时是成功的,但是到 crontab 中试图让它定期执行时就是会出错。

修复:在脚本文件的开头,强制要求导入环境变量,可保万无一失。

这样的话,脚本的头部一律以下列格式开头:

#!/bin/sh
. /etc/profile
. ~/.bash_profile

以 AutoRefreshData.sh 为例,它的头部则由

[She@She ~]$ cat /home/She/data/AutoRefreshData.sh #!/bin/bash
...
MatlabFile= 改为:

[She@She ~]$ vi /home/She/data/AutoRefreshData.sh #!/bin/sh . /etc/profile . ~/.bash_profile
...
MatlabFile=2>running.err &
之后,更新 crontab 中的运行时间,立即测试,一切正常,不再报错。

cat ~/running.log < M A T L A B (R) > copyright 1984-2015 The MathWorks,Inc. R2015b (8.6.0.267246) 64-bit (glnxa64) August 20,2015 For online documentation,see http://www.mathworks.com/support For product information,visit www.mathworks.com. >> >> >> >> >> >> >> /mnt/L/Data/matFile/jpl16228.mat >> [She@She ~]$ cat ~/running.err [She@She ~]$

相关文章

Centos下搭建性能监控Spotlight
CentOS 6.3下Strongswan搭建IPSec VPN
在CentOS6.5上安装Skype与QQ
阿里云基于centos6.5主机VPN配置
CentOS 6.3下配置multipah
CentOS安装、配置APR和tomcat-native