如何验证sqlplus可以连接?

J. *_*mel 8 unix oracle sqlplus

我想知道是否有可能以sqlplus某种方式获取输出以发现我的数据库是否已启动.

我想在数据库上运行脚本列表,但在此之前,我想知道数据库是否已启动并运行我的脚本.

这是我尝试过的:

 sqlplus /@DB1 << EOF
 > select 1 from dual;
 > EOF
Run Code Online (Sandbox Code Playgroud)

它无法连接,但sqlplus的返回码仍然说"一切正常"!

SQL*Plus: Release 11.2.0.4.0 Production on Mon Nov 28 10:06:41 2016

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

ERROR:
ORA-12505: TNS:listener does not currently know of SID given in connect
descriptor


Enter user-name: SP2-0306: Invalid option.
Usage: CONN[ECT] [{logon|/|proxy} [AS {SYSDBA|SYSOPER|SYSASM}] [edition=value]]
where  ::= [/][@]
       ::= [][/][@]
Enter user-name: ju@srv:/tmp/jcho $ echo $?
0

我知道我可以grep我的测试查询的结果,像这样:

sqlplus /@DB1 << EOF
  select 'ALL_GOOD_BOY' from dual;
EOF
Run Code Online (Sandbox Code Playgroud)

呼叫:

1如果连接有效,0 则给出行,否则:

$ a.sh |grep ALL_GOOD_BOY|wc -l
Run Code Online (Sandbox Code Playgroud)

......这对我来说似乎有很多步骤.在"无法连接"的模式下设置sqlplus的任何其他方式都会给出"错误"返回码?

J. *_*mel 6

感谢@Kacper提供的参考,我可以sqlplus /nolog根据我的情况进行调整; 这是个主意:

  1. sqlplus只打开没有连接
  2. 设置一个特定的返回代码SQLERROR- 这是connect失败时发生的事情
  3. 可以像往常一样在调用者脚本中收集返回代码:

sqlplus /nolog << EOF
 WHENEVER SQLERROR EXIT 50
 WHENEVER OSERROR EXIT 66
 connect /@${MISTERY_DB}
 exit;
EOF
Run Code Online (Sandbox Code Playgroud)

然后电话:

/ju $ export MISTERY_DB="eg_NON_EXISTING_DB"
/ju $ a.sh
SQL*Plus: Release 11.2.0.4.0 Production on Tue Nov 29 08:43:44 2016
Copyright (c) 1982, 2013, Oracle.  All rights reserved.
SQL> SQL> SQL> ERROR:
  ORA-12154: TNS:could not resolve the connect identifier specified
/ju $ echo $?
50
Run Code Online (Sandbox Code Playgroud)

还相关:在shell脚本中连接到sqlplus并运行SQL脚本