[CentOS] 解決 crontab 沒法讀取環境變量的問題

參考資料:http://blog.slogra.com/post-238.htmlhtml

1. 問題描述

  一段數據處理的 shell 程序,在 shell 中手動運行,能夠正確執行。可是,把它放在 crontab 列表裏,就會報錯,提示 "matlab: command not found."。node

  AutoRefreshData.sh 的部份內容以下:shell

[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 可正確執行:bash

[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 中:jvm

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

 在 crontab 中,運行報錯,結果以下:post

[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 中試圖讓它按期執行時就是會出錯。測試

修復:在腳本文件的開頭,強制要求導入環境變量,可保萬無一失。spa

這樣的話,腳本的頭部一概如下列格式開頭:code

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

 

以 AutoRefreshData.sh 爲例,它的頭部則由orm

[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 &

改成:

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

 

以後,更新 crontab 中的運行時間,當即測試,一切正常,再也不報錯。

[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 ~]$

Done。

相關文章
相關標籤/搜索