Managing error handling while running sqlplus from shell scripts Managing error handling while running sqlplus from shell scripts shell shell

Managing error handling while running sqlplus from shell scripts


What Max says is correct. Try this modified script

#!/bin/shecho "Please enter evaluate database username"read eval_userecho "Please enter evaluate database password"read eval_passecho "Please enter the database name"read db_nameLOGFILE=shell_log.txtsqlplus -s /nolog <<-EOF>> ${LOGFILE}WHENEVER OSERROR EXIT 9;WHENEVER SQLERROR EXIT SQL.SQLCODE;connect $eval_user/$eval_pass@$db_nameDBMS_OUTPUT.put_line('Connected to db');EOFsql_return_code=$?if [ $sql_return_code != 0 ]thenecho "The upgrade script failed. Please refer to the log results.txt for more information"echo "Error code $sql_return_code"exit 0;fi

Please note the use of sql_return_code to capture the SQLPLUS return code.

The DBMS_OUTPUT statement should fail with error - "SP2-0734: unknown command beginning...". You can find the error message in log file.

It is possible to trap the sp2 errors in SQLPLUS 11g using the error logging facility. Please have a look at http://tkyte.blogspot.co.uk/2010/04/new-thing-about-sqlplus.html for more information.


it might be possible that your whenever statements are executed after connection to the db has been established (since you have mentioned them afterwards). Try the following code :-

$ORACLE_HOME/bin/sqlplus -s /nolog <<-EOF>> ${LOGFILE}WHENEVER OSERROR EXIT 9;WHENEVER SQLERROR EXIT SQL.SQLCODE;connect $eval_user/$eval_pass@$db_nameDBMS_OUTPUT.put_line('Connected to db');EOF


Aji's answer with

WHENEVER SQLERROR EXIT SQL.SQLCODE;

and then using

sql_return_code=$?

is not correct (or not correct in most cases). See details below.


Shell script in an UNIX OS can return codes up to 255. E.g. "ORA-12703 this character set conversion is not supported" return code should be 12703, but it doesn't fit into UNIX 8-bit return code.
Actually I just did a test and ran a bad SQL that fails with "ORA-00936: missing expression" -
sqlplus returned 168 (!).
So the actual return code 936 was wrapped at 256 and just remainder got returned. 936%256=168.


On Windows this probably could work (not tested), but not on UNIX (tested as explained above).


The only reliable mechanism is probably to spool results into a log file and then do something like

tail -n 25 spool.log | egrep "ORA-" | tail -n 1 | cut -d: -f1 | cut -d- -f2

So it would grep the spool log file and then cut actual latest ORA-code.