I'm trying to create a script that does the following:
Connect with SQLplus to my oracle db. Do a select 1 from dual; and when I don't get a value back. Than put the $DATE in a logfile.
What I have until now:
#!/bin/bash
# values
GEN_ERR=1 #error 1 code
USER=username
PASS=mypass
SIDORA=oracle.db
LOG=/var/log/failure.log
#Login to the DB
sqlplus -s /nolog <<EOF
connect $USER/$PASS@$SIDORA
select 1 from dual;
EOF
errorCode=$? # checks if the last operation (sqlplus) was completed successfully or not
if [ ${errorCode} -ne 0 ]
then
echo "DATE" >> $LOG
exit ${CRED_ERR}
fi
I believe the status code $? gives the status of the command sqlplus in your above script and not for the 'select ...' statement inside it . IMO re-direct the output to a file and check for its size.Something like..
OUTFILE=outfile.txt # Declare a output file
#Login to the DB
sqlplus -s /nolog <<EOF > $OUTFILE
connect $USER/$PASS@$SIDORA
select 1 from dual;
exit;
EOF
if [[ ! -s ${OUTFILE} ]]
then
echo "$DATE" >> $LOG
exit ${CRED_ERR}
fi
Or you could grep for any 'ORA-..' error in the out file to check if the connection is success or not.
Ok I've finished the script.
Any remarks? Please let me know.
#!/bin/bash
# values
USER=username
PASS=password
SIDORA=sid
LOG=/var/log/$SIDORA.log
DATUM=date
#Login to the DB
sqlplus -s /nolog <<EOF > tmpfile.log
connect $USER/$PASS@$SIDORA
select 1 from dual;
EOF
errorCode=$(head -2 tmpfile.log | awk '{ print $1 }' | grep 1)
# checks if the last operation (sqlplus) was completed successfully or not
if [ $errorCode != 1 ];
then
$DATUM >> $LOG
fi
The only potential problem I see is if you get an error and the "ORA-" message contains a 1 (for example: ORA-01017 Invalid username or password), you would get a false positive.
You could just return your results to a variable, test the exit code and the results and react accordingly:
I don't have my server up to test, but this should work for you.
I use ksh so please excuse any syntax differences...
#
# Using <<-EOF allows you to TAB (can not be spaces)
# the EOF over for code alignment, if necessary.
#
DB_STATUS=$(sqlplus -s /nolog <<-EOF
connect $USER/$PWD@$DB
set pages 0 trimout on trimspool on
set echo off termout off sqlprompt ''
select 1 from dual;
exit
EOF)
EXIT_CODE=$?
if [[ "${EXIT_CODE}" -ne 0 ]] && [[ "${DB_STATUS}" -ne 1 ]]; then
echo "Error mesage" >> ${LOG}
fi