參考資料:http://blog.slogra.com/post-238.html
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='/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。