crontab环境变量问题分析

发布时间:2020-09-25编辑:脚本学堂
本文介绍了crontab定时计划任务中环境变量的一些问题,感兴趣的朋友参考下。

test.sh脚本,使用到了环境变量
 

复制代码 代码示例:
#!/bin/sh
sqlplus /nolog<<ENDOFINPUT
    whenever sqlerror exit 20;
    whenever oserror exit 20;
    connect hxl/hxl;
    variable cnt number;
    begin
    select Count(1) into :cnt from dual;
    if :cnt = 0 then
     :cnt:=0;
    else
     :cnt:=99;
    end if;
    end;
/
exit :cnt
ENDOFINPUT
flag=$?
echo $flag

手工执行没有问题:
 

复制代码 代码示例:

[etl@node1 shell]$ ./test.sh

SQL*Plus: Release 11.2.0.3.0 Production on Fri Mar 7 11:29:19 2014

Copyright (c) 1982, 2011, Oracle.  All rights reserved.

SQL> SQL> SQL> Connected.
SQL> SQL>   2    3    4    5    6    7    8    9 
PL/SQL procedure successfully completed.

SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options
99
[etl@node1 shell]$

crontab内容:
 

复制代码 代码示例:
[etl@node1 log]$ crontab -l
20 11 * * * /home/etl/shell/test.sh >>$HOME/log/output_test.log 2>&1

crontab中无法执行:
 

复制代码 代码示例:
[etl@node1 log]$ more output_test.log
/home/etl/shell/test.sh: line 2: sqlplus: command not found
127

经检查是环境变量问题(相关阅读:linux环境变量的设置与查看  设置Linux环境变量的三种方法  Linux环境变量配置小结  了解Linux环境变量),将如下两句添加到脚本中,即可解决问题:
 

. /etc/profile
. ~/.bash_profile