crontab非root用户定时任务踩坑——脚本单独运行正常,放在定时任务运行就报错。
oracle用户,定时插入数据脚本
脚本如下
#!/bin/bash
#---Insert 500 pieces of data into the database---
sqlplus / as sysdba << EOF
conn test01/shuyi123
select count(*) from test01;
insert into jd_test01 value( select rownum as id,rownum+10 as task_id,dbms_random.string('x', 40) as server_uuid,dbms_random.string('x',40) as proxy_uuid,dbms_random.string('x',40) as repo_uuid from dual connect by level<=500);
select count(*) from test01;
commit;
exit;
EOF
定时任务日志:提示sqlplus 命令未找到
cat /var/spool/mail/oracle
From oracle@ora.localdomain Tue Jul 28 18:00:02 2020
Return-Path: <oracle@ora.localdomain>
X-Original-To: oracle
Delivered-To: oracle@ora.localdomain
Received: by ora.localdomain (Postfix, from userid 1000)
id 0F1F91AE5459; Tue, 28 Jul 2020 18:00:01 +0800 (CST)
From: "(Cron Daemon)" <oracle@ora.localdomain>
To: oracle@ora.localdomain
Subject: Cron <oracle@ora> /oradata/insert_data.sh
Content-Type: text/plain; charset=UTF-8
Auto-Submitted: auto-generated
Precedence: bulk
X-Cron-Env: <XDG_SESSION_ID=10>
X-Cron-Env: <XDG_RUNTIME_DIR=/run/user/1000>
X-Cron-Env: <LANG=zh_CN.UTF-8>
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/oracle>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=oracle>
X-Cron-Env: <USER=oracle>
Message-Id: <20200728100002.0F1F91AE5459@ora.localdomain>
Date: Tue, 28 Jul 2020 18:00:01 +0800 (CST)
/oradata/insert_data.sh:行7: sqlplus: 未找到命令
究其原因,是因为定时任务在执行脚本的时候读取不了oracle用户环境变量,找不到sqlplus命令
所以在脚本中加入下面一行:
source /home/oracle/.bash_profile
定时任务即可正常执行。