Unix/Linux下,shell脚本调用sqlplus的几种方式介绍:
一、最简单的shell调用sqlplus
#!/bin/bash
sqlplus -S /nolog > sqlplus.log <<EOF
conn scott/scott
select sysdate from dual;
quit
EOF
二、sqlplus返回执行结果给shell
方法一:
#!/bin/bash
biz_date=`sqlplus -S scott/scott <<EOF
set heading off
set pagesize 0;
set feedback off;
set verify off;
set echo off;
select sysdate from dual;
exit
EOF`
echo $biz_date
(注意:等号两侧不能有空格.)
[oracle@toughhou shell]$ vi sqlplus.sh
21-NOV-13
方法二:
注意sqlplus段使用 col .. new_value .. 定义了变量并带参数exit, 然后自动赋给了shell的$?
#!/bin/bash
sqlplus -S scott/scott <<EOF
set heading off
set pagesize 0;
set feedback off;
set verify off;
set echo off;
col biz_date new_value v_biz_date
select sysdate biz_date from dual;
exit v_biz_date
EOF
biz_date="$?"
[oracle@toughhou shell]$ vi sqlplus.sh
sqlplus.sh: line 11: warning: here-document at line 1 delimited by end-of-file (wanted `EOF')
21-NOV-13
这里出warning是因为EOF后面有空格。(注意:结尾出的EOF后面不能有任何字符)
去掉空格后结果如下:
[oracle@toughhou shell]$ vi sqlplus.sh
22-NOV-13
三、shell程序传递参数给sqlplus
sqlplus里可以直接使用, 赋变量的等号两侧不能有空格不能有空格.
接收到的变量不能加引号。“select sysdate from $tb;"不能写成"select sysdate from '$tb';"
#!/bin/bash
tb=dualsqlplus -S scott/scott <<EOF
set heading off
set pagesize 0;
set feedback off;
set verify off;
set echo off;
select sysdate from $tb;
exit
EOF
[oracle@toughhou shell]$ sh sqlplus.sh
22-NOV-13
四、为了安全要求每次执行shell都手工输入密码
#!/bin/bash
echo -n "Enter db password for scott: "
read pwdsqlplus -S scott/$pwd <<EOF
set heading off
set pagesize 0;
set feedback off;
set verify off;
set echo off;
select sysdate from dual;
exit
EOF
[oracle@toughhou shell]$ sh sqlplus.sh
Enter db password for scott: scott
22-NOV-13
五、为了安全从文件读取密码
对密码文件设置权限, 只有用户自己才能读写.
[oracle@toughhou shell]$ echo scott > scott.pwd
[oracle@toughhou shell]$ chmod 500 soctt.pwd
[oracle@toughhou shell]$ chmod 500 scott.pwd
[oracle@toughhou shell]$ ls -l scott.pwd
-r-x------ 1 oracle oinstall 6 Nov 22 00:17 scott.pwd
#!/bin/bash
pwd=`cat scott.pwd`sqlplus -S scott/$pwd <<EOF
set heading off
set pagesize 0;
set feedback off;
set verify off;
set echo off;
select sysdate from dual;
exit
EOF