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
