简体   繁体   中英

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. No log is created. But it works when I use something like spool exec_proc_daily_2o.log . Why is the variable $logfile not replace.

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 . 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:

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. I have made few changes as I don't I like to refer to &1 and &2 in SQL script everywhere.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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