1) 在/etc/profile里创建了环境变量,发现在指定用户下创建的cronjob运行期不能找到对应的环境变量的值(例如$PATH),在crontab下发现默认$PATH=/bin:/usr/bin。如调用的程序不在上述路径,则程序会报错:xxx not found.
上述解决的方案,最好的解决方法是在xxx.sh中第一行这样写: #!/bin/bash -l
这样就是以登录方式执行shell script,你可以通过 man bash来查看是否支持 -l 这个参数。
为什么不用程序的绝对路径呢? 因为deploy一个脚本到多个主机,这样都指定绝对路径相当繁琐而且难维护。
如果不支持-l这个参数呢? 你可以: crontab -e,然后添加一行,如下:
PATH=/your/path1:/your/path2:... 或在你的脚本中添加一行: source /etc/profile
2)shell script执行中,常常有部分命令有 异常代码和异常信息 返回。我们需要捕获这些异常,示例代码如下:
result=$(${mysqlpath} --skip-column-names -h"$1" -D"xxxx" -u$CONFIG_DBUSER -p$CONFIG_DBPASSWORD -e"$checking_sql" >"$log_output_file" 2>&1) if [ "$?" -ne 0 ]; then result=`cat"${log_output_file}"` errMsg="Error occurred while checking zzz on ${1},msg=${result}" echo -e "$errMsg" | mail -s "$errMsg" "${EMAIL_TO}" fi
3)shell script 调试,参考: http://www.ibm.com/developerworks/cn/linux/l-cn-shell-debug/index.html