Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check database connectivity using Shell script

I am trying to write a shell script to check database connectivity. Within my script I am using the command

sqlplus uid/pwd@database-schemaname

to connect to my Oracle database.

Now I want to save the output generated by this command (before it drops to SQL prompt) in a temp file and then grep / find the string "Connected to" from that file to see if the connectivity is fine or not.

Can anyone please help me to catch the output and get out of that prompt and test whether connectivity is fine?

like image 582
mohona Avatar asked Sep 23 '10 14:09

mohona


4 Answers

none of the proposed solutions works for me, as my script is executed in machines running several countries, with different locales, I can't simply check for one String simply because this string in the other machine is translated to a different language. As a solution I'm using SQLcl

https://www.oracle.com/database/technologies/appdev/sqlcl.html

which is compatible with all sql*plus scripts and allow you to test the database connectivity like this:

echo "disconnect" | sql -L $DB_CONNECTION_STRING > /dev/null || fail "cannot check connectivity with the database, check your settings"
like image 63
Mtruchado Avatar answered Oct 04 '22 08:10

Mtruchado


Use a script like this:

#!/bin/sh
echo "exit" | sqlplus -L uid/pwd@dbname | grep Connected > /dev/null
if [ $? -eq 0 ] 
then
   echo "OK"
else
   echo "NOT OK"
fi

echo "exit" assures that your program exits immediately (this gets piped to sqlplus). -L assures that sqlplus won't ask for password if credentials are not ok (which would make it get stuck as well).

(> /dev/null just hides output from grep, which we don't need because the results are accessed via $? in this case)

like image 32
Jochem Avatar answered Oct 17 '22 05:10

Jochem


You can avoid the SQL prompt by doing:

sqlplus uid/pwd@database-schemaname < /dev/null

SqlPlus exits immediately.

Now just grep the output of the above as:

if sqlplus uid/pwd@database-schemaname < /dev/null | grep 'Connected to'; then
   # have connectivity to Oracle
else
   # No connectivity
fi
like image 3
codaddict Avatar answered Oct 17 '22 03:10

codaddict


#! /bin/sh  

if echo "exit;" | sqlplus UID/PWD@database-schemaname 2>&1 | grep -q "Connected to"
then echo connected OK
else echo connection FAIL
fi

Not knowing whether the "Connected to" message is put to standard output or standard error, this checks both. "qrep -q" instead of "grep... >/dev/null" assumes Linux.

like image 3
frayser Avatar answered Oct 17 '22 03:10

frayser