在crontab中执行shell脚本的问题

crontab中记录的编写比较简单,下面是一个示例:

0 2 * * * /app/tpssapp/ftpsrc/tools/statTables/statTables.sh > /app/tpssapp/ftpsrc/tools/statTables/statTables.log

表示每天2点执行/app/tpssapp/ftpsrc/tools/statTables/statTables.sh。
这里有个问题是,有时候,因为shell脚本的问题,导致在自己在命令行中运行的shell脚本和crontab中运行的效果不一样。这个问题的原因就是,在shell命令中shell脚本使用了系统的环境变量,一个用户的命令行,起码读取的2个环境变量配置文件:/etc/profile和${HOME}/.bash_profile。如果shell脚本在crontab执行出现问题,原因就是它在执行的时候,没有加载这两个环境变量配置文件。所以,我们需要在shell脚本中自己去指定让shell去设定环境变量。
代码如下:

#! /bin/sh
echo `pwd`
echo `id`
USER_HOME=/home/`whoami`
. /etc/profile
if [ -f ${USER_HOME}/.bash_profile ];
then
       echo ${USER_HOME}/.bash_profile
        . ${USER_HOME}/.bash_profile
fi

BASE_PATH=/app/tpssapp/ftpsrc/tools/statTables
cd ${BASE_PATH}
java -jar statTables-v2.0.jar

脚本上面的部分,可以作为一个通用的东西,配置在每一个脚本中。

原文地址:https://www.cnblogs.com/babyha/p/10038968.html