简体   繁体   English

如何在bash脚本中将变量传递给sqlplus

[英]How to pass a variable to sqlplus in a bash script

I have a script like below. 我有一个如下的脚本。 My goal is write to a log file terminating with the current date and time as filename and spool to the file: 我的目标是写入一个以当前日期和时间作为文件名结尾的日志文件,并假脱机到该文件:

#!/bin/bash

year=`date +%Y`
month=`date +%m`
day=`date +%d`
prefixe=$month$day$year
logfile="/home/oracle/logs/exec_proc_daily_20_"$prefixe.log

sqlplus / "as sysdba" <<EOF
spool on
spool $logfile
execute Proc_RFC_MAJ_MV_ITIN;
execute Proc_RFC_MAJ_MV_REFGEO;
commit;
quit
EOF

When I execute the script, the spool $logfile gives an error. 当我执行脚本时, spool $logfile给出错误。 No log is created. 没有日志创建。 But it works when I use something like spool exec_proc_daily_2o.log . 但是当我使用spool exec_proc_daily_2o.log类的东西时,它可以工作。 Why is the variable $logfile not replace. 为什么变量$logfile不被替换。

After doing alot of digging, I found the solution to the problem. 经过大量挖掘之后,我找到了解决问题的方法。 On the line sqlplus / "as sysdba" <<EOF , I passed the variable like this sqlplus / as sysdba <<EOF >$logfile . sqlplus / "as sysdba" <<EOF ,我传递了像sqlplus / as sysdba <<EOF >$logfile这样的变量。 So the complete code should be: 因此完整的代码应为:

#!/bin/bash

year=`date +%Y`
month=`date +%m`
day=`date +%d`
prefixe=$month$day$year
logfile="/home/oracle/logs/exec_proc_daily_20_"$prefixe.log

sqlplus / "as sysdba" <<EOF >$logfile
spool on
spool $logfile
execute Proc_RFC_MAJ_MV_ITIN;
execute Proc_RFC_MAJ_MV_REFGEO;
commit;
quit
EOF

[Edited with working example] Pass a variable to sqlplus: [使用工作示例进行编辑]将变量传递给sqlplus:

demo.sh 演示

export myvar1="hello"
export myvar2=123
sqlplus "/ as sysdba" @demo.sql $myvar1 $myvar2
echo "---shell is complete---"

demo.sql 演示程序

select 'first variable is &1 and second is &2'
from dual;
exit

@Beege answer works in Linux env. @Beege答案在Linux环境中有效。 I have made few changes as I don't I like to refer to &1 and &2 in SQL script everywhere. 我所做的更改很少,因为我不想在所有地方都在SQL脚本中引用&1和&2。

myvar1="hello"
myvar2=123
sqlplus username/password@SID @oracle_variabling_passing.sql $myvar1 $myvar2
echo "---shell is complete---"

oracle_variabling_passing.sql: oracle_variabling_passing.sql:

define first_var=&1
define second_var=&2
select 'first variable is &&first_var and second is &&second_var'
from dual;
exit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM