Search code examples
linuxbashoracle-databaseunixsolaris

Storing oracle query results into bash variable


declare -a result=`$ORACLE_HOME/bin/sqlplus -silent  $DBUSER/$DBPASSWORD@$DB << EOF $SQLPLUSOPTIONS $roam_query exit; EOF`

I am trying to pull data from an oracle database and populate a bash variable. The select query works however it returns multiple rows and those rows are returned as a long continuous string. I want to capture each row from the database in an array index for example:

index[0] = row 1 information
index[1] = row 2 information

Please help. All suggestions are appreciated. I checked all documentation without no luck. Thank you. I am using solaris unix


Solution

  • If you have bash version 4, you can use the readarray -t command to do this. Any vaguely recent linux should have bash v4, but I don't know about Solaris.

    BTW, I'd also recommend putting double-quotes around variable references (e.g. "$DBUSER/$DBPASSWORD@$DB" instead of just $DBUSER/$DBPASSWORD@$DB) (except in here-documents), using $( ) instead of backticks, and using lower- or mixed-case variable names (there are a bunch of all-caps names with special meanings, and if you use one of those by accident, weird things can happen).

    I'm not sure I have the here-document (the SQL commands) right, but here's roughly how I'd do it:

    readarray -t result < <("$oracle_home/bin/sqlplus" -silent  "$dbuser/$dbpassword@$db" << EOF
    $sqlplusoptions $roam_query
    exit;
    EOF
    )